"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 { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

const schema = z.object({
  date: z.string().min(1, "Date is required"),
  unit: z.string().max(20).default("A"),
  label: z.string().max(120).optional(),
  notes: z.string().optional(),
});

type FormData = z.infer<typeof schema>;

interface Props {
  projectId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCreate: (day: { id: string; date: string; unit: string; label: string | null }) => Promise<void> | void;
}

export function NewShootDayDialog({ projectId, open, onOpenChange, onCreate }: Props) {
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      date: format(new Date(), "yyyy-MM-dd"),
      unit: "A",
    },
  });

  async function onSubmit(data: FormData) {
    setLoading(true);
    try {
      const res = await fetch("/api/shoot-log/days", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ projectId, ...data }),
      });
      if (!res.ok) throw new Error("Failed to create shoot day");
      const { day } = await res.json();
      onCreate(day);
      reset({ date: format(new Date(), "yyyy-MM-dd"), unit: "A" });
      onOpenChange(false);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md bg-zinc-900 border-zinc-800">
        <DialogHeader>
          <DialogTitle className="text-white">New Shoot Day</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-zinc-400 text-xs">Date *</Label>
              <Input
                type="date"
                {...register("date")}
                className="bg-zinc-800 border-zinc-700 text-white"
              />
              {errors.date && (
                <p className="text-red-400 text-xs">{errors.date.message}</p>
              )}
            </div>

            <div className="space-y-1.5">
              <Label className="text-zinc-400 text-xs">Unit</Label>
              <Input
                {...register("unit")}
                placeholder="A"
                className="bg-zinc-800 border-zinc-700 text-white"
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <Label className="text-zinc-400 text-xs">Label (optional)</Label>
            <Input
              {...register("label")}
              placeholder="e.g. Ext. Warehouse — Night"
              className="bg-zinc-800 border-zinc-700 text-white"
            />
          </div>

          <div className="space-y-1.5">
            <Label className="text-zinc-400 text-xs">Notes (optional)</Label>
            <Input
              {...register("notes")}
              placeholder="Any notes about this shoot day..."
              className="bg-zinc-800 border-zinc-700 text-white"
            />
          </div>

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Create Day"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
