"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { FormField } from "@/components/shared/form-field";
import { LookupSelect } from "@/components/shared/lookup-select";
import { useResidenceTypes } from "@/lib/hooks/use-lookups";
import type { ResidenceResponse } from "@/lib/api/residences";
import { Loader2 } from "lucide-react";

// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------

const residenceSchema = z.object({
  name: z.string().min(1, "Name is required"),
  property_type_id: z.number().optional(),
  street_address: z.string().optional(),
  apartment_unit: z.string().optional(),
  city: z.string().optional(),
  state_province: z.string().optional(),
  postal_code: z.string().optional(),
  country: z.string().optional(),
  bedrooms: z.number().optional(),
  bathrooms: z.number().optional(),
  square_footage: z.number().optional(),
  year_built: z.number().min(1800).max(2100).optional(),
  description: z.string().optional(),
});

type ResidenceFormData = z.infer<typeof residenceSchema>;

// ---------------------------------------------------------------------------
// Props
// ---------------------------------------------------------------------------

interface ResidenceFormProps {
  residence?: ResidenceResponse;
  onSubmit: (data: ResidenceFormData) => void;
  loading?: boolean;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function ResidenceForm({ residence, onSubmit, loading = false }: ResidenceFormProps) {
  const { data: residenceTypes } = useResidenceTypes();

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<ResidenceFormData>({
    resolver: zodResolver(residenceSchema),
    defaultValues: {
      name: residence?.name ?? "",
      property_type_id: residence?.property_type_id ?? undefined,
      street_address: residence?.street_address ?? "",
      apartment_unit: residence?.apartment_unit ?? "",
      city: residence?.city ?? "",
      state_province: residence?.state_province ?? "",
      postal_code: residence?.postal_code ?? "",
      country: residence?.country ?? "",
      bedrooms: residence?.bedrooms ?? undefined,
      bathrooms: residence?.bathrooms ?? undefined,
      square_footage: residence?.square_footage ?? undefined,
      year_built: residence?.year_built ?? undefined,
      description: residence?.description ?? "",
    },
  });

  const propertyTypeId = watch("property_type_id");

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
      {/* Name & Property Type */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField label="Name" htmlFor="name" error={errors.name?.message} required>
          <Input
            id="name"
            placeholder="My Home"
            aria-invalid={!!errors.name}
            {...register("name")}
          />
        </FormField>

        <FormField label="Property Type" htmlFor="property_type_id">
          <LookupSelect
            items={residenceTypes}
            value={propertyTypeId}
            onValueChange={(v) => setValue("property_type_id", v)}
            placeholder="Select type..."
          />
        </FormField>
      </div>

      {/* Address */}
      <div className="space-y-4">
        <h3 className="text-sm font-medium text-muted-foreground">Address</h3>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <FormField label="Street Address" htmlFor="street_address">
            <Input
              id="street_address"
              placeholder="123 Main St"
              {...register("street_address")}
            />
          </FormField>

          <FormField label="Apartment / Unit" htmlFor="apartment_unit">
            <Input
              id="apartment_unit"
              placeholder="Apt 4B"
              {...register("apartment_unit")}
            />
          </FormField>

          <FormField label="City" htmlFor="city">
            <Input id="city" placeholder="Austin" {...register("city")} />
          </FormField>

          <FormField label="State / Province" htmlFor="state_province">
            <Input
              id="state_province"
              placeholder="TX"
              {...register("state_province")}
            />
          </FormField>

          <FormField label="Postal Code" htmlFor="postal_code">
            <Input
              id="postal_code"
              placeholder="78701"
              {...register("postal_code")}
            />
          </FormField>

          <FormField label="Country" htmlFor="country">
            <Input
              id="country"
              placeholder="US"
              {...register("country")}
            />
          </FormField>
        </div>
      </div>

      {/* Property Details */}
      <div className="space-y-4">
        <h3 className="text-sm font-medium text-muted-foreground">Property Details</h3>
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
          <FormField label="Bedrooms" htmlFor="bedrooms">
            <Input
              id="bedrooms"
              type="number"
              placeholder="3"
              {...register("bedrooms", { valueAsNumber: true })}
            />
          </FormField>

          <FormField label="Bathrooms" htmlFor="bathrooms">
            <Input
              id="bathrooms"
              type="number"
              placeholder="2"
              {...register("bathrooms", { valueAsNumber: true })}
            />
          </FormField>

          <FormField label="Sq. Footage" htmlFor="square_footage">
            <Input
              id="square_footage"
              type="number"
              placeholder="1500"
              {...register("square_footage", { valueAsNumber: true })}
            />
          </FormField>

          <FormField
            label="Year Built"
            htmlFor="year_built"
            error={errors.year_built?.message}
          >
            <Input
              id="year_built"
              type="number"
              placeholder="2000"
              aria-invalid={!!errors.year_built}
              {...register("year_built", { valueAsNumber: true })}
            />
          </FormField>
        </div>
      </div>

      {/* Description */}
      <FormField label="Description" htmlFor="description">
        <Textarea
          id="description"
          placeholder="Notes about this property..."
          rows={3}
          {...register("description")}
        />
      </FormField>

      {/* Submit */}
      <div className="flex justify-end">
        <Button type="submit" disabled={loading}>
          {loading && <Loader2 className="size-4 mr-2 animate-spin" />}
          {residence ? "Save Changes" : "Create Residence"}
        </Button>
      </div>
    </form>
  );
}
