"use client";

import { useState } from "react";
import { Plus, Sparkles, 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 { TagPicker } from "./tag-picker";
import type { Priority, Tag, TaskStatus, TaskTemplate } from "@/types";
import type { TaskTemplateInput } from "@/hooks/use-task-templates";

interface TaskTemplatesModalProps {
  open: boolean;
  onClose: () => void;
  templates: TaskTemplate[];
  tags: Tag[];
  onCreateTag: (name: string, color: string) => Promise<Tag>;
  onCreateTemplate: (input: TaskTemplateInput) => Promise<void>;
  onDeleteTemplate: (id: string) => Promise<void>;
  onUseTemplate: (template: TaskTemplate) => Promise<void>;
}

const PRIORITIES: { 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" },
];

const STATUSES: { value: TaskStatus; label: string }[] = [
  { value: "todo", label: "To do" },
  { value: "in_progress", label: "In progress" },
  { value: "done", label: "Done" },
  { value: "cancelled", label: "Cancelled" },
];

function emptyForm() {
  return {
    name: "",
    title: "",
    description: "",
    priority: "none" as Priority,
    status: "todo" as TaskStatus,
    tagIds: [] as string[],
  };
}

export function TaskTemplatesModal({
  open,
  onClose,
  templates,
  tags,
  onCreateTag,
  onCreateTemplate,
  onDeleteTemplate,
  onUseTemplate,
}: TaskTemplatesModalProps) {
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(emptyForm());
  const [submitting, setSubmitting] = useState(false);
  const [usingId, setUsingId] = useState<string | null>(null);

  function tagsFor(template: TaskTemplate) {
    return template.tag_ids
      .map((id) => tags.find((tag) => tag.id === id))
      .filter((tag): tag is Tag => !!tag);
  }

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

    setSubmitting(true);
    await onCreateTemplate({
      name: form.name.trim(),
      title: form.title.trim(),
      description: form.description.trim(),
      priority: form.priority,
      status: form.status,
      tag_ids: form.tagIds,
    });
    setSubmitting(false);
    setForm(emptyForm());
    setShowForm(false);
  }

  async function handleUse(template: TaskTemplate) {
    setUsingId(template.id);
    await onUseTemplate(template);
    setUsingId(null);
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Task templates"
      description="Save recurring task setups once, then spin up new tasks from them in a click."
      className="max-w-lg"
    >
      <div className="space-y-4">
        {templates.length === 0 && !showForm && (
          <div className="rounded-lg border border-dashed border-border py-8 text-center">
            <p className="text-sm text-muted-foreground">No templates yet.</p>
          </div>
        )}

        {templates.length > 0 && (
          <div className="space-y-2">
            {templates.map((template) => (
              <div
                key={template.id}
                className="flex items-start justify-between gap-3 rounded-lg border border-border bg-background/50 p-3"
              >
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium">{template.name}</p>
                  <p className="truncate text-xs text-muted-foreground">{template.title}</p>
                  {tagsFor(template).length > 0 && (
                    <div className="mt-1.5 flex flex-wrap gap-1">
                      {tagsFor(template).map((tag) => (
                        <span
                          key={tag.id}
                          className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium text-white"
                          style={{ backgroundColor: tag.color }}
                        >
                          {tag.name}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
                <div className="flex shrink-0 items-center gap-1.5">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    disabled={usingId === template.id}
                    onClick={() => handleUse(template)}
                  >
                    <Sparkles className="h-3.5 w-3.5" />
                    {usingId === template.id ? "Creating…" : "Use"}
                  </Button>
                  <button
                    type="button"
                    onClick={() => onDeleteTemplate(template.id)}
                    className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-destructive cursor-pointer"
                    title="Delete template"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}

        {showForm ? (
          <form onSubmit={handleCreate} className="space-y-3 rounded-lg border border-border p-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Template name</Label>
              <Input
                placeholder="e.g. Weekly report"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                autoFocus
                required
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Task title</Label>
              <Input
                placeholder="Task title when created"
                value={form.title}
                onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
                required
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Description</Label>
              <Textarea
                placeholder="Add a description..."
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
                className="min-h-[60px] text-sm"
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">Status</Label>
                <Select
                  value={form.status}
                  onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as TaskStatus }))}
                >
                  {STATUSES.map((s) => (
                    <option key={s.value} value={s.value}>{s.label}</option>
                  ))}
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">Priority</Label>
                <Select
                  value={form.priority}
                  onChange={(e) => setForm((f) => ({ ...f, priority: e.target.value as Priority }))}
                >
                  {PRIORITIES.map((p) => (
                    <option key={p.value} value={p.value}>{p.label}</option>
                  ))}
                </Select>
              </div>
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Tags</Label>
              <TagPicker
                tags={tags}
                selectedIds={form.tagIds}
                onChange={(ids) => setForm((f) => ({ ...f, tagIds: ids }))}
                onCreateTag={onCreateTag}
              />
            </div>

            <div className="flex justify-end gap-2 pt-1">
              <Button
                type="button"
                variant="ghost"
                onClick={() => {
                  setShowForm(false);
                  setForm(emptyForm());
                }}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={!form.name.trim() || !form.title.trim() || submitting}>
                {submitting ? "Saving…" : "Save template"}
              </Button>
            </div>
          </form>
        ) : (
          <Button type="button" variant="outline" className="w-full" onClick={() => setShowForm(true)}>
            <Plus className="h-3.5 w-3.5" />
            New template
          </Button>
        )}
      </div>
    </Modal>
  );
}
