"use client";

import { useState } from "react";
import Link from "next/link";
import { ArrowRight, CheckCircle2, Loader2, ListChecks, Plus, Trash2 } from "lucide-react";
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { useTasks } from "@/hooks/use-tasks";
import type { ActionChecklistItem } from "./action-checklist-node";

export function ActionChecklistBlockView({ node, updateAttributes, editor }: NodeViewProps) {
  const items = node.attrs.items as ActionChecklistItem[];
  const tasksCreated = !!node.attrs.tasksCreated;
  const editable = editor.isEditable;
  const { createTask } = useTasks();
  const [converting, setConverting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function toggle(index: number) {
    updateAttributes({ items: items.map((item, i) => (i === index ? { ...item, done: !item.done } : item)) });
  }

  function updateText(index: number, text: string) {
    updateAttributes({ items: items.map((item, i) => (i === index ? { ...item, text } : item)) });
  }

  function addItem() {
    updateAttributes({ items: [...items, { text: "", done: false }] });
  }

  function removeItem(index: number) {
    updateAttributes({ items: items.filter((_, i) => i !== index) });
  }

  async function convertToTasks() {
    setConverting(true);
    setError(null);
    try {
      for (const item of items) {
        if (!item.text.trim()) continue;
        await createTask({ title: item.text.trim() });
      }
      updateAttributes({ tasksCreated: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not create tasks");
    } finally {
      setConverting(false);
    }
  }

  return (
    <NodeViewWrapper className="my-3">
      <div className="rounded-2xl border border-border bg-card/60 p-4" contentEditable={false}>
        <div className="mb-3 flex items-center gap-1.5 text-[12px] font-semibold text-muted-foreground">
          <ListChecks className="h-3.5 w-3.5" />
          Action checklist
        </div>

        <div className="space-y-1.5">
          {items.map((item, index) => (
            <div key={index} className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={item.done}
                onChange={() => toggle(index)}
                className="h-4 w-4 shrink-0 rounded border-border"
              />
              {editable ? (
                <input
                  value={item.text}
                  onChange={(e) => updateText(index, e.target.value)}
                  placeholder="Checklist item…"
                  className="min-w-0 flex-1 rounded-md border border-transparent bg-transparent px-1.5 py-1 text-[13px] outline-none focus:border-border focus:bg-background"
                />
              ) : (
                <span className="min-w-0 flex-1 text-[13px] text-foreground/80">{item.text}</span>
              )}
              {editable && (
                <button type="button" onClick={() => removeItem(index)} className="shrink-0 text-muted-foreground hover:text-destructive">
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              )}
            </div>
          ))}
        </div>

        {editable && (
          <button
            type="button"
            onClick={addItem}
            className="mt-2 flex items-center gap-1.5 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground"
          >
            <Plus className="h-3.5 w-3.5" />
            Add item
          </button>
        )}

        {error && <p className="mt-2 text-[11.5px] text-destructive">{error}</p>}

        <div className="mt-3 border-t border-border pt-3">
          {tasksCreated ? (
            <Link
              href="/tasks"
              className="flex items-center gap-1.5 text-[12.5px] font-semibold text-emerald-500 hover:underline"
            >
              <CheckCircle2 className="h-3.5 w-3.5" />
              Created as real tasks — open Tasks
              <ArrowRight className="h-3 w-3" />
            </Link>
          ) : (
            <button
              type="button"
              onClick={() => void convertToTasks()}
              disabled={converting || items.every((i) => !i.text.trim())}
              className="flex items-center gap-1.5 rounded-lg border border-sky-500/25 bg-sky-500/[0.08] px-3 py-1.5 text-[12.5px] font-semibold text-sky-400 transition-colors hover:bg-sky-500/[0.14] disabled:opacity-50"
            >
              {converting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              {converting ? "Creating tasks…" : "Turn into real tasks"}
            </button>
          )}
        </div>
      </div>
    </NodeViewWrapper>
  );
}
