"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
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 { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createProject } from "@/actions/projects";
import { useToast } from "@/components/ui/use-toast";

const projectSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  code: z.string().min(2, "Project code required").regex(/^[A-Z0-9_\-]+$/i, "Alphanumeric, dash, underscore"),
  showId: z.string().min(1, "Show ID required").max(10, "Max 10 chars").regex(/^[A-Z0-9_]+$/i, "Letters, numbers, underscore only"),
  projectType: z.enum(["STANDARD", "EPISODIC"]).default("STANDARD"),
  description: z.string().optional(),
  clientId: z.string().optional(),
  deadline: z.string().optional(),
});

type ProjectFormValues = z.infer<typeof projectSchema>;

interface NewProjectDialogProps {
  open: boolean;
  onClose: () => void;
  clients?: { id: string; company: string }[];
  onSuccess?: (projectId: string) => void;
}

export function NewProjectDialog({
  open,
  onClose,
  clients = [],
  onSuccess,
}: NewProjectDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();
  const router = useRouter();

  const {
    register,
    handleSubmit,
    setValue,
    reset,
    formState: { errors },
  } = useForm<ProjectFormValues>({
    resolver: zodResolver(projectSchema),
    defaultValues: { projectType: "STANDARD" },
  });

  const onSubmit = async (data: ProjectFormValues) => {
    setIsSubmitting(true);
    try {
      const result = await createProject({
        name: data.name,
        code: data.code.toUpperCase(),
        showId: data.showId.toUpperCase(),
        projectType: data.projectType,
        description: data.description,
        clientId: data.clientId || undefined,
        deadline: data.deadline ? new Date(data.deadline) : undefined,
      });
      toast({ title: "Project created" });
      reset();
      router.push(`/projects/${result.project.id}`);
      router.refresh();
      onSuccess?.(result.project.id);
      onClose();
    } catch (err) {
      toast({
        title: "Failed to create project",
        description: (err as Error).message,
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>New Project</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-1.5 col-span-2">
              <Label htmlFor="name">Project Name *</Label>
              <Input id="name" placeholder="Stellar Montage" {...register("name")} />
              {errors.name && (
                <p className="text-xs text-destructive">{errors.name.message}</p>
              )}
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="code">Code *</Label>
              <Input
                id="code"
                placeholder="NOVA-25"
                className="uppercase"
                {...register("code")}
              />
              {errors.code && (
                <p className="text-xs text-destructive">{errors.code.message}</p>
              )}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="showId">Show ID *</Label>
              <Input
                id="showId"
                placeholder="PRJX"
                className="uppercase"
                maxLength={10}
                {...register("showId")}
              />
              {errors.showId && (
                <p className="text-xs text-destructive">{errors.showId.message}</p>
              )}
              <p className="text-xs text-muted-foreground">Used in shot codes (e.g. PRJX_SC010_0010)</p>
            </div>
            <div className="space-y-1.5">
              <Label>Project Type *</Label>
              <Select
                defaultValue="STANDARD"
                onValueChange={(v) => setValue("projectType", v as "STANDARD" | "EPISODIC")}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="STANDARD">Standard</SelectItem>
                  <SelectItem value="EPISODIC">Episodic</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              placeholder="Brief description of this project..."
              {...register("description")}
              className="min-h-[70px]"
            />
          </div>

          {clients.length > 0 && (
            <div className="space-y-1.5">
              <Label>Client</Label>
              <Select onValueChange={(v) => setValue("clientId", v)}>
                <SelectTrigger>
                  <SelectValue placeholder="Select client (optional)" />
                </SelectTrigger>
                <SelectContent>
                  {clients.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.company}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="space-y-1.5">
            <Label htmlFor="deadline">Deadline</Label>
            <Input id="deadline" type="date" {...register("deadline")} />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Creating..." : "Create Project"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
