"use client";

import { useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Modal } from "@/components/ui/modal";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import type { Priority, ProjectTemplate } from "@/types";

const TEMPLATE_COLORS = [
  "#6366f1",
  "#8b5cf6",
  "#ec4899",
  "#ef4444",
  "#f97316",
  "#eab308",
  "#22c55e",
  "#06b6d4",
  "#3b82f6",
  "#64748b",
];

const TEMPLATE_ICONS = [
  "📁",
  "🚀",
  "💼",
  "🎯",
  "📊",
  "🔧",
  "📝",
  "🎨",
  "💡",
  "📦",
  "⚡",
  "🌟",
];

const TEMPLATE_HEALTH_OPTIONS = [
  { value: "on_track" as const, label: "On track" },
  { value: "at_risk" as const, label: "At risk" },
  { value: "stuck" as const, label: "Stuck" },
];

const PRIORITY_OPTIONS: Array<{ value: Priority; label: string }> = [
  { value: "none", label: "No priority" },
  { value: "low", label: "Low" },
  { value: "medium", label: "Medium" },
  { value: "high", label: "High" },
  { value: "urgent", label: "Urgent" },
];

interface TemplateTaskDraft {
  id: string;
  title: string;
  description: string;
  priority: Priority;
  deadlineOffsetDays: string;
}

interface ProjectTemplateFormProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: {
    name: string;
    description: string;
    goal: string;
    color: string;
    icon: string;
    health: ProjectTemplate["health"];
    tasks: Array<{
      title: string;
      description?: string;
      priority?: Priority;
      deadline_offset_days?: number | null;
    }>;
  }) => Promise<void>;
  template?: ProjectTemplate | null;
}

function getInitialTasks(template?: ProjectTemplate | null): TemplateTaskDraft[] {
  if (template?.tasks && template.tasks.length > 0) {
    return template.tasks.map((task) => ({
      id: crypto.randomUUID(),
      title: task.title,
      description: task.description || "",
      priority: task.priority,
      deadlineOffsetDays:
        typeof task.deadline_offset_days === "number"
          ? String(task.deadline_offset_days)
          : "",
    }));
  }

  return [
    {
      id: crypto.randomUUID(),
      title: "",
      description: "",
      priority: "none",
      deadlineOffsetDays: "",
    },
  ];
}

export function ProjectTemplateForm({
  open,
  onClose,
  onSubmit,
  template,
}: ProjectTemplateFormProps) {
  const isEditing = !!template;

  const [name, setName] = useState(template?.name || "");
  const [description, setDescription] = useState(template?.description || "");
  const [goal, setGoal] = useState(template?.goal || "");
  const [color, setColor] = useState(template?.color || TEMPLATE_COLORS[0]);
  const [icon, setIcon] = useState(template?.icon || TEMPLATE_ICONS[0]);
  const [health, setHealth] = useState<ProjectTemplate["health"]>(
    template?.health || "on_track"
  );
  const [tasks, setTasks] = useState<TemplateTaskDraft[]>(getInitialTasks(template));
  const [submitting, setSubmitting] = useState(false);

  function updateTask(
    index: number,
    field: keyof TemplateTaskDraft,
    value: string
  ) {
    setTasks((prev) =>
      prev.map((task, taskIndex) =>
        taskIndex === index ? { ...task, [field]: value } : task
      )
    );
  }

  function addTask() {
    setTasks((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        title: "",
        description: "",
        priority: "none",
        deadlineOffsetDays: "",
      },
    ]);
  }

  function removeTask(index: number) {
    setTasks((prev) => {
      if (prev.length === 1) {
        return [
          {
            id: crypto.randomUUID(),
            title: "",
            description: "",
            priority: "none",
            deadlineOffsetDays: "",
          },
        ];
      }
      return prev.filter((_, taskIndex) => taskIndex !== index);
    });
  }

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!name.trim() || submitting) return;

    setSubmitting(true);
    await onSubmit({
      name: name.trim(),
      description: description.trim(),
      goal: goal.trim(),
      color,
      icon,
      health,
      tasks: tasks
        .filter((task) => task.title.trim().length > 0)
        .map((task) => ({
          title: task.title.trim(),
          description: task.description.trim() || undefined,
          priority: task.priority,
          deadline_offset_days:
            task.deadlineOffsetDays.trim().length > 0
              ? Number.parseInt(task.deadlineOffsetDays, 10) || 0
              : null,
        })),
    });
    setSubmitting(false);
    onClose();
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? "Edit template" : "New template"}
      className="max-w-3xl"
    >
      <form onSubmit={handleSubmit} className="space-y-5">
        <div className="flex items-center justify-center py-2">
          <div
            className="flex h-16 w-16 items-center justify-center rounded-2xl text-3xl"
            style={{ backgroundColor: `${color}20` }}
          >
            {icon}
          </div>
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <div className="space-y-1.5 md:col-span-2">
            <Label>Template name</Label>
            <Input
              placeholder="Client onboarding"
              value={name}
              onChange={(event) => setName(event.target.value)}
              autoFocus
              required
            />
          </div>

          <div className="space-y-1.5 md:col-span-2">
            <Label className="text-xs text-muted-foreground">Template description</Label>
            <Textarea
              placeholder="Explain when this template should be used and what it sets up."
              value={description}
              onChange={(event) => setDescription(event.target.value)}
              className="min-h-[88px]"
            />
          </div>

          <div className="space-y-1.5 md:col-span-2">
            <Label className="text-xs text-muted-foreground">Default project goal</Label>
            <Input
              placeholder="What should this project achieve?"
              value={goal}
              onChange={(event) => setGoal(event.target.value)}
            />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Default health</Label>
            <Select
              value={health}
              onChange={(event) =>
                setHealth(event.target.value as ProjectTemplate["health"])
              }
            >
              {TEMPLATE_HEALTH_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </Select>
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Default color</Label>
            <div className="flex flex-wrap gap-1.5">
              {TEMPLATE_COLORS.map((item) => (
                <button
                  key={item}
                  type="button"
                  onClick={() => setColor(item)}
                  className={cn(
                    "h-7 w-7 rounded-full transition-transform",
                    color === item && "scale-110 ring-2 ring-ring ring-offset-2"
                  )}
                  style={{ backgroundColor: item }}
                />
              ))}
            </div>
          </div>

          <div className="space-y-1.5 md:col-span-2">
            <Label className="text-xs text-muted-foreground">Default icon</Label>
            <div className="flex flex-wrap gap-1">
              {TEMPLATE_ICONS.map((emoji) => (
                <button
                  key={emoji}
                  type="button"
                  onClick={() => setIcon(emoji)}
                  className={cn(
                    "flex h-9 w-9 items-center justify-center rounded-lg text-lg transition-all",
                    icon === emoji ? "bg-accent ring-2 ring-ring" : "hover:bg-accent"
                  )}
                >
                  {emoji}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-border/70 p-4">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h3 className="text-sm font-semibold">Starter tasks</h3>
              <p className="text-xs text-muted-foreground">
                These tasks are created automatically when the template is used.
              </p>
            </div>
            <Button type="button" variant="outline" size="sm" onClick={addTask}>
              <Plus className="h-4 w-4" />
              Add task
            </Button>
          </div>

          <div className="mt-4 space-y-3">
            {tasks.map((task, index) => (
              <div
                key={task.id}
                className="rounded-xl border border-border/70 bg-muted/20 p-4"
              >
                <div className="grid gap-3 md:grid-cols-[1.2fr_0.8fr_0.7fr_auto]">
                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Task title</Label>
                    <Input
                      value={task.title}
                      onChange={(event) =>
                        updateTask(index, "title", event.target.value)
                      }
                      placeholder="Kickoff call"
                    />
                  </div>

                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Priority</Label>
                    <Select
                      value={task.priority}
                      onChange={(event) =>
                        updateTask(index, "priority", event.target.value)
                      }
                    >
                      {PRIORITY_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>

                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Due in days</Label>
                    <Input
                      type="number"
                      value={task.deadlineOffsetDays}
                      onChange={(event) =>
                        updateTask(index, "deadlineOffsetDays", event.target.value)
                      }
                      placeholder="3"
                    />
                  </div>

                  <div className="flex items-end">
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeTask(index)}
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>

                <div className="mt-3 space-y-1.5">
                  <Label className="text-xs text-muted-foreground">Task description</Label>
                  <Textarea
                    value={task.description}
                    onChange={(event) =>
                      updateTask(index, "description", event.target.value)
                    }
                    placeholder="Optional instructions or context for this starter task."
                    className="min-h-[72px]"
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-end gap-2 pt-2">
          <Button type="button" variant="ghost" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit" disabled={!name.trim() || submitting}>
            {submitting
              ? isEditing
                ? "Saving..."
                : "Creating..."
              : isEditing
                ? "Save template"
                : "Create template"}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
