import { useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { motion, useReducedMotion } from "framer-motion";
import { Trash2, Copy } from "lucide-react";
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
  ContextMenuSeparator,
} from "@/components/ui/context-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import type { BoardMeta } from "@/types/board";
import { useAppStore } from "@/stores/app-store";
import { useBoardStore } from "@/stores/board-store";
import { useToastStore } from "@/stores/toast-store";
import { deleteBoard, loadBoard, saveBoard } from "@/lib/storage";

interface BoardCardProps {
  board: BoardMeta;
  index?: number;
}

export function BoardCard({ board, index = 0 }: BoardCardProps) {
  const [confirmDelete, setConfirmDelete] = useState(false);
  const prefersReducedMotion = useReducedMotion();
  const addToast = useToastStore((s) => s.addToast);

  const setView = useAppStore((s) => s.setView);
  const addRecentBoard = useAppStore((s) => s.addRecentBoard);
  const refreshBoards = useAppStore((s) => s.refreshBoards);
  const openBoard = useBoardStore((s) => s.openBoard);

  const relativeTime = formatDistanceToNow(new Date(board.updatedAt), {
    addSuffix: true,
  });

  async function handleOpen() {
    await openBoard(board.id);
    setView({ type: "board", boardId: board.id });
    addRecentBoard(board.id);
  }

  async function handleDelete() {
    await deleteBoard(board.id);
    await refreshBoards();
    setConfirmDelete(false);
    addToast(`"${board.title}" deleted`, "info");
  }

  async function handleDuplicate() {
    const original = await loadBoard(board.id);
    const { ulid } = await import("ulid");
    const ts = new Date().toISOString();
    const duplicated = {
      ...original,
      id: ulid(),
      title: `${original.title} (copy)`,
      createdAt: ts,
      updatedAt: ts,
    };
    await saveBoard(duplicated);
    await refreshBoards();
    addToast(`"${board.title}" duplicated`, "success");
  }

  return (
    <motion.div
      initial={prefersReducedMotion ? false : { opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ type: "spring", stiffness: 300, damping: 25, delay: index * 0.05 }}
    >
      <ContextMenu>
        <ContextMenuTrigger asChild>
          <button
            onClick={handleOpen}
            className="group flex w-full flex-col rounded-lg bg-pylon-surface shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md text-left"
          >
            {/* Color accent stripe */}
            <div
              className="h-1 w-full rounded-t-lg"
              style={{ backgroundColor: board.color }}
            />

            <div className="flex flex-col gap-2 p-4">
              {/* Board title */}
              <h3 className="font-heading text-lg text-pylon-text">
                {board.title}
              </h3>

              {/* Stats line */}
              <p className="font-mono text-xs text-pylon-text-secondary">
                {board.cardCount} card{board.cardCount !== 1 ? "s" : ""} &middot;{" "}
                {board.columnCount} column{board.columnCount !== 1 ? "s" : ""}
              </p>

              {/* Relative time */}
              <p className="font-mono text-xs text-pylon-text-secondary">
                {relativeTime}
              </p>
            </div>
          </button>
        </ContextMenuTrigger>

        <ContextMenuContent>
          <ContextMenuItem onClick={handleDuplicate}>
            <Copy className="size-4" />
            Duplicate
          </ContextMenuItem>
          <ContextMenuSeparator />
          <ContextMenuItem
            variant="destructive"
            onClick={() => setConfirmDelete(true)}
          >
            <Trash2 className="size-4" />
            Delete
          </ContextMenuItem>
        </ContextMenuContent>
      </ContextMenu>

      {/* Delete confirmation dialog */}
      <Dialog open={confirmDelete} onOpenChange={setConfirmDelete}>
        <DialogContent className="bg-pylon-surface sm:max-w-sm">
          <DialogHeader>
            <DialogTitle className="font-heading text-pylon-text">
              Delete Board
            </DialogTitle>
            <DialogDescription className="text-pylon-text-secondary">
              Are you sure you want to delete &ldquo;{board.title}&rdquo;? This
              action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="ghost"
              onClick={() => setConfirmDelete(false)}
              className="text-pylon-text-secondary"
            >
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </motion.div>
  );
}
