"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 { createTask } from "@/actions/tasks";
import { useToast } from "@/components/ui/use-toast";
import { TaskType, ShotPriority } from "@prisma/client";

const TASK_TYPE_LABELS: Record<TaskType, string> = {
  TRACK: "Track",
  ROTO: "Roto",
  KEY: "Key",
  COMP: "Comp",
  FX: "FX",
  LIGHTING: "Lighting",
  RENDER: "Render",
  ANIMATION: "Animation",
  MODEL: "Model",
  TEXTURE: "Texture",
  RIG: "Rig",
  LOOKDEV: "Lookdev",
  GENERAL: "General",
};

// Common shot task templates
const SHOT_TEMPLATES: TaskType[] = ["TRACK", "ROTO", "KEY", "COMP", "FX", "LIGHTING"];
// Common asset task templates
const ASSET_TEMPLATES: TaskType[] = ["MODEL", "TEXTURE", "RIG", "LOOKDEV"];

const taskSchema = z.object({
  title: z.string().min(1, "Title is required"),
  description: z.string().optional(),
  type: z.nativeEnum(TaskType),
  priority: z.nativeEnum(ShotPriority),
  dueDate: z.string().optional(),
  estimatedHours: z.string().optional(),
  assignedArtistId: z.string().optional(),
});

type TaskFormValues = z.infer<typeof taskSchema>;

interface Artist {
  id: string;
  name: string | null;
  email: string;
}

interface NewTaskDialogProps {
  projectId: string;
  shotId?: string;
  assetId?: string;
  artists: Artist[];
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  /** If provided, pre-fills the task type and title */
  prefillType?: TaskType;
}

export function NewTaskDialog({
  projectId,
  shotId,
  assetId,
  artists,
  open,
  onClose,
  onSuccess,
  prefillType,
}: NewTaskDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();
  const router = useRouter();

  const templates = shotId ? SHOT_TEMPLATES : assetId ? ASSET_TEMPLATES : [];

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<TaskFormValues>({
    resolver: zodResolver(taskSchema),
    defaultValues: {
      type: prefillType ?? "GENERAL",
      priority: "NORMAL",
      title: prefillType ? TASK_TYPE_LABELS[prefillType] : "",
    },
  });

  const selectedType = watch("type");

  const applyTemplate = (type: TaskType) => {
    setValue("type", type);
    setValue("title", TASK_TYPE_LABELS[type]);
  };

  const onSubmit = async (data: TaskFormValues) => {
    setIsSubmitting(true);
    try {
      await createTask({
        ...data,
        projectId,
        shotId: shotId ?? "",
        assetId: assetId ?? "",
        assignedArtistId: (data.assignedArtistId === "__none__" ? undefined : data.assignedArtistId) ?? undefined,
        estimatedHours: data.estimatedHours ? Number(data.estimatedHours) : undefined,
      });
      toast({ title: "Task created" });
      reset();
      router.refresh();
      onSuccess?.();
      onClose();
    } catch (err) {
      toast({
        title: "Failed to create task",
        description: (err as Error).message,
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

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

        {templates.length > 0 && (
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Quick add</Label>
            <div className="flex flex-wrap gap-1.5">
              {templates.map((t) => (
                <button
                  key={t}
                  type="button"
                  onClick={() => applyTemplate(t)}
                  className={`px-2.5 py-1 rounded text-xs font-medium border transition-colors ${
                    selectedType === t
                      ? "bg-amber-500/20 text-amber-400 border-amber-500/40"
                      : "bg-zinc-800 text-zinc-400 border-zinc-700 hover:border-zinc-500"
                  }`}
                >
                  + {TASK_TYPE_LABELS[t]}
                </button>
              ))}
            </div>
          </div>
        )}

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5 col-span-2">
              <Label htmlFor="title">Title *</Label>
              <Input id="title" placeholder="Task title" {...register("title")} />
              {errors.title && (
                <p className="text-xs text-destructive">{errors.title.message}</p>
              )}
            </div>

            <div className="space-y-1.5">
              <Label>Type</Label>
              <Select
                value={selectedType}
                onValueChange={(v) => setValue("type", v as TaskType)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {(Object.keys(TASK_TYPE_LABELS) as TaskType[]).map((t) => (
                    <SelectItem key={t} value={t}>
                      {TASK_TYPE_LABELS[t]}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1.5">
              <Label>Priority</Label>
              <Select
                defaultValue="NORMAL"
                onValueChange={(v) => setValue("priority", v as ShotPriority)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="LOW">Low</SelectItem>
                  <SelectItem value="NORMAL">Normal</SelectItem>
                  <SelectItem value="HIGH">High</SelectItem>
                  <SelectItem value="URGENT">Urgent</SelectItem>
                </SelectContent>
              </Select>
            </div>

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

            <div className="space-y-1.5">
              <Label htmlFor="estimatedHours">Est. Hours</Label>
              <Input
                id="estimatedHours"
                type="number"
                min="0"
                step="0.5"
                placeholder="0"
                {...register("estimatedHours")}
              />
            </div>

            {artists.length > 0 && (
              <div className="space-y-1.5 col-span-2">
                <Label>Assign Artist</Label>
                <Select
                  defaultValue=""
                  onValueChange={(v) => setValue("assignedArtistId", v === "__none__" ? undefined : v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Unassigned" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">Unassigned</SelectItem>
                    {artists.map((a) => (
                      <SelectItem key={a.id} value={a.id}>
                        {a.name ?? a.email}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              placeholder="What needs to be done?"
              rows={2}
              {...register("description")}
            />
          </div>

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