"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { 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({
  name: z.string().min(1, "Name required").max(100),
  description: z.string().max(300).optional(),
});
type FormData = z.infer<typeof schema>;

interface Props {
  shootDayId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCreated: (setup: { id: string; name: string }) => Promise<void> | void;
}

export function NewSetupDialog({ shootDayId, open, onOpenChange, onCreated }: Props) {
  const [loading, setLoading] = useState(false);

  const { register, handleSubmit, reset, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { name: "" },
  });

  async function onSubmit(data: FormData) {
    setLoading(true);
    try {
      const res = await fetch(`/api/shoot-log/days/${shootDayId}/setups`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error("Failed to create setup");
      const { setup } = await res.json();
      onCreated(setup);
      reset();
      onOpenChange(false);
    } finally {
      setLoading(false);
    }
  }

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

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="space-y-1.5">
            <Label className="text-zinc-400 text-xs">Setup Name *</Label>
            <Input
              {...register("name")}
              placeholder="A, B, or descriptive name"
              autoFocus
              className="bg-zinc-800 border-zinc-700 text-white"
            />
            {errors.name && <p className="text-red-400 text-xs">{errors.name.message}</p>}
          </div>

          <div className="space-y-1.5">
            <Label className="text-zinc-400 text-xs">Description (optional)</Label>
            <Input
              {...register("description")}
              placeholder="Camera position, location..."
              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 Setup"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
