"use client";

import { useState } from "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 { Goal, Project } from "@/types";

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

const PROJECT_ICONS = [
  "📁", "🚀", "💼", "🎯", "📊", "🔧", "📝", "🎨",
  "💡", "🏠", "📦", "⚡", "🌟", "🔥", "💎", "🎮",
];

interface ProjectFormProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: {
    name: string;
    color: string;
    icon: string;
    description: string;
    goal: string;
    goal_id: string | null;
    health: "on_track" | "at_risk" | "stuck";
  }) => Promise<void>;
  project?: Project | null;
  goals: Goal[];
}

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

export function ProjectForm({
  open,
  onClose,
  onSubmit,
  project,
  goals,
}: ProjectFormProps) {
  const isEditing = !!project;

  const [name, setName] = useState(project?.name || "");
  const [color, setColor] = useState(project?.color || PROJECT_COLORS[0]);
  const [icon, setIcon] = useState(project?.icon || PROJECT_ICONS[0]);
  const [description, setDescription] = useState(project?.description || "");
  const [goal, setGoal] = useState(project?.goal || "");
  const [goalId, setGoalId] = useState(project?.goal_id || "");
  const [health, setHealth] = useState<Project["health"]>(project?.health || "on_track");
  const [submitting, setSubmitting] = useState(false);

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

    setSubmitting(true);
    await onSubmit({
      name: name.trim(),
      color,
      icon,
      description: description.trim(),
      goal: goal.trim(),
      goal_id: goalId || null,
      health,
    });
    setSubmitting(false);
    onClose();
  }

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

        {/* Name */}
        <div className="space-y-1.5">
          <Label>Project name</Label>
          <Input
            placeholder="My Project"
            value={name}
            onChange={(e) => setName(e.target.value)}
            autoFocus
            required
            className="text-center"
          />
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-muted-foreground">Goal</Label>
          <Input
            placeholder="What does success look like for this project?"
            value={goal}
            onChange={(e) => setGoal(e.target.value)}
          />
        </div>

        {goals.length > 0 && (
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Aligned goal</Label>
            <Select
              value={goalId}
              onChange={(e) => setGoalId(e.target.value)}
            >
              <option value="">No linked goal</option>
              {goals.map((item) => (
                <option key={item.id} value={item.id}>
                  {item.icon} {item.title}
                </option>
              ))}
            </Select>
          </div>
        )}

        <div className="space-y-1.5">
          <Label className="text-xs text-muted-foreground">Description</Label>
          <Textarea
            placeholder="Add context, scope, or notes for this project..."
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="min-h-[90px]"
          />
        </div>

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

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

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

        {/* Actions */}
        <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 changes"
              : "Create project"}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
