"use client";

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

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FormField } from "@/components/shared/form-field";
import { useCreateResidence } from "@/lib/hooks/use-residences";
import { useOnboardingStore } from "@/stores/onboarding";

// ---------------------------------------------------------------------------
// Schema (simplified for onboarding)
// ---------------------------------------------------------------------------

const createResidenceSchema = z.object({
  name: z.string().min(1, "Name is required"),
  street_address: z.string().optional(),
  city: z.string().optional(),
});

type CreateResidenceFormData = z.infer<typeof createResidenceSchema>;

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

export function CreateResidenceStep() {
  const { nextStep, prevStep, setResidenceId } = useOnboardingStore();
  const createResidence = useCreateResidence();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CreateResidenceFormData>({
    resolver: zodResolver(createResidenceSchema),
    defaultValues: {
      name: "",
      street_address: "",
      city: "",
    },
  });

  const onSubmit = (data: CreateResidenceFormData) => {
    createResidence.mutate(
      {
        name: data.name,
        street_address: data.street_address || undefined,
        city: data.city || undefined,
      },
      {
        onSuccess: (residence) => {
          setResidenceId(residence.id);
          nextStep();
        },
      }
    );
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <h2 className="text-2xl font-bold tracking-tight">
          Create your residence
        </h2>
        <p className="text-muted-foreground">
          You can add more details later. Just give it a name to get started.
        </p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <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="Street Address" htmlFor="street_address">
          <Input
            id="street_address"
            placeholder="123 Main St"
            {...register("street_address")}
          />
        </FormField>

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

        {createResidence.error && (
          <p className="text-sm text-destructive">
            {createResidence.error instanceof Error
              ? createResidence.error.message
              : "Failed to create residence. Please try again."}
          </p>
        )}

        <div className="flex items-center justify-between pt-2">
          <Button type="button" variant="ghost" onClick={prevStep}>
            Back
          </Button>
          <Button type="submit" disabled={createResidence.isPending}>
            {createResidence.isPending && (
              <Loader2 className="size-4 mr-2 animate-spin" />
            )}
            Create Residence
          </Button>
        </div>
      </form>
    </div>
  );
}
