"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { format } from "date-fns";
import { CalendarIcon, Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FormField } from "@/components/shared/form-field";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { useCreateTask } from "@/lib/hooks/use-tasks";
import { useOnboardingStore } from "@/stores/onboarding";
import { cn } from "@/lib/utils";

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

const firstTaskSchema = z.object({
  title: z.string().min(1, "Task title is required"),
});

type FirstTaskFormData = z.infer<typeof firstTaskSchema>;

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

export function FirstTaskStep() {
  const { nextStep, prevStep, residenceId } = useOnboardingStore();
  const createTask = useCreateTask();
  const [dueDate, setDueDate] = useState<Date | undefined>(undefined);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FirstTaskFormData>({
    resolver: zodResolver(firstTaskSchema),
    defaultValues: {
      title: "",
    },
  });

  const onSubmit = (data: FirstTaskFormData) => {
    if (!residenceId) return;

    createTask.mutate(
      {
        residence_id: residenceId,
        title: data.title,
        due_date: dueDate ? format(dueDate, "yyyy-MM-dd") : undefined,
      },
      {
        onSuccess: () => {
          nextStep();
        },
      }
    );
  };

  const handleSkip = () => {
    nextStep();
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <h2 className="text-2xl font-bold tracking-tight">
          Add your first task
        </h2>
        <p className="text-muted-foreground">
          Create a maintenance task to keep your property in shape. You can skip
          this for now.
        </p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          label="Task Title"
          htmlFor="title"
          error={errors.title?.message}
          required
        >
          <Input
            id="title"
            placeholder="e.g., Change HVAC filter"
            aria-invalid={!!errors.title}
            {...register("title")}
          />
        </FormField>

        <FormField label="Due Date" htmlFor="due_date">
          <Popover>
            <PopoverTrigger asChild>
              <Button
                id="due_date"
                type="button"
                variant="outline"
                className={cn(
                  "w-full justify-start text-left font-normal",
                  !dueDate && "text-muted-foreground"
                )}
              >
                <CalendarIcon className="mr-2 size-4" />
                {dueDate ? format(dueDate, "PPP") : "Pick a date (optional)"}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <Calendar
                mode="single"
                selected={dueDate}
                onSelect={setDueDate}
                disabled={(date) => date < new Date(new Date().setHours(0, 0, 0, 0))}
              />
            </PopoverContent>
          </Popover>
        </FormField>

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

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