"use client";

import { useState } from "react";
import { useTheme } from "next-themes";
import { Pencil, Trash2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { MDEditor, MarkdownPreview } from "@/components/markdown/markdown-widgets";
import { useBoard } from "@/components/board/board-context";
import { formatDateTime } from "@/lib/format";
import type { TodoDTO } from "@/types/board";

const TITLE_MAX = 20;

export function TodoEditDialog({
  todo,
  groupId,
  categoryId,
  open,
  onOpenChange,
}: {
  todo: TodoDTO;
  groupId: string;
  categoryId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { editTodo, removeTodo } = useBoard();
  const { resolvedTheme } = useTheme();
  const colorMode = resolvedTheme === "dark" ? "dark" : "light";

  const [title, setTitle] = useState(todo.title);
  const [details, setDetails] = useState(todo.details ?? "");
  // Details gets its own view/edit toggle, same as the group's Notes
  // editor -- markdown renders as a preview until you choose to edit it,
  // rather than always showing raw source in a plain textarea.
  const [editingDetails, setEditingDetails] = useState(false);
  const [pending, setPending] = useState(false);

  function handleOpenChange(next: boolean) {
    if (next) {
      setTitle(todo.title);
      setDetails(todo.details ?? "");
      setEditingDetails(false);
    }
    onOpenChange(next);
  }

  async function handleSave() {
    const trimmed = title.trim();
    if (!trimmed) return;
    setPending(true);
    const ok = await editTodo(todo.id, groupId, categoryId, {
      title: trimmed,
      details: details.trim() || null,
    });
    setPending(false);
    if (ok) onOpenChange(false);
  }

  async function handleDelete() {
    setPending(true);
    await removeTodo(todo.id, groupId, categoryId);
    setPending(false);
    onOpenChange(false);
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-2xl" data-color-mode={colorMode}>
        <DialogHeader>
          <DialogTitle>Edit to-do</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor={`edit-title-${todo.id}`}>Title</Label>
            <Input
              id={`edit-title-${todo.id}`}
              value={title}
              maxLength={TITLE_MAX}
              onChange={(e) => setTitle(e.target.value)}
            />
            <p className="text-right text-xs text-muted-foreground">
              {title.length}/{TITLE_MAX}
            </p>
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label>Details</Label>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-6 gap-1 px-2 text-xs text-muted-foreground"
                onClick={() => setEditingDetails((v) => !v)}
              >
                <Pencil className="size-3" />
                {editingDetails ? "Preview" : "Edit"}
              </Button>
            </div>

            {editingDetails ? (
              <MDEditor
                value={details}
                onChange={(v) => setDetails(v ?? "")}
                height={220}
              />
            ) : details ? (
              <div className="max-h-48 overflow-y-auto rounded-md border p-3">
                <MarkdownPreview source={details} />
              </div>
            ) : (
              <p className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">
                No details yet. Click Edit to add some -- links, lists, etc.
              </p>
            )}
          </div>
        </div>

        <div className="flex flex-wrap gap-x-4 gap-y-1 border-t pt-3 text-xs text-muted-foreground">
          <span>Created {formatDateTime(todo.createdAt)}</span>
          <span>Updated {formatDateTime(todo.updatedAt)}</span>
          {todo.completed && todo.completedAt && (
            <span>Completed {formatDateTime(todo.completedAt)}</span>
          )}
        </div>

        <DialogFooter className="sm:justify-between">
          <Button
            variant="ghost"
            className="text-destructive hover:text-destructive gap-2"
            onClick={handleDelete}
            disabled={pending}
          >
            <Trash2 className="size-4" />
            Delete
          </Button>
          <Button onClick={handleSave} disabled={pending || !title.trim()}>
            {pending ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
