import { useState, useRef, useEffect } from "react";
import { MoreHorizontal } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useBoardStore } from "@/stores/board-store";
import type { Column, ColumnWidth } from "@/types/board";

interface ColumnHeaderProps {
  column: Column;
  cardCount: number;
  filteredCount?: number;
}

const COLOR_PRESETS = [
  { hue: "160", label: "Teal" },
  { hue: "240", label: "Blue" },
  { hue: "300", label: "Purple" },
  { hue: "350", label: "Pink" },
  { hue: "25", label: "Red" },
  { hue: "55", label: "Orange" },
  { hue: "85", label: "Yellow" },
  { hue: "130", label: "Lime" },
  { hue: "200", label: "Cyan" },
  { hue: "0", label: "Slate" },
];

export function ColumnHeader({ column, cardCount, filteredCount }: ColumnHeaderProps) {
  const [editing, setEditing] = useState(false);
  const [editValue, setEditValue] = useState(column.title);
  const inputRef = useRef<HTMLInputElement>(null);

  const updateColumnTitle = useBoardStore((s) => s.updateColumnTitle);
  const deleteColumn = useBoardStore((s) => s.deleteColumn);
  const setColumnWidth = useBoardStore((s) => s.setColumnWidth);
  const setColumnColor = useBoardStore((s) => s.setColumnColor);
  const setColumnWipLimit = useBoardStore((s) => s.setColumnWipLimit);
  const toggleColumnCollapse = useBoardStore((s) => s.toggleColumnCollapse);

  useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editing]);

  function commitRename() {
    const trimmed = editValue.trim();
    if (trimmed && trimmed !== column.title) {
      updateColumnTitle(column.id, trimmed);
    } else {
      setEditValue(column.title);
    }
    setEditing(false);
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Enter") {
      commitRename();
    } else if (e.key === "Escape") {
      setEditValue(column.title);
      setEditing(false);
    }
  }

  function handleWidthChange(width: ColumnWidth) {
    setColumnWidth(column.id, width);
  }

  return (
    <div className="flex items-center justify-between border-b border-border px-3 pb-2 pt-3">
      <div className="flex items-center gap-2 overflow-hidden">
        {editing ? (
          <input
            ref={inputRef}
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            onBlur={commitRename}
            onKeyDown={handleKeyDown}
            aria-label="Column title"
            className="h-5 w-full bg-transparent font-mono text-xs font-semibold uppercase tracking-widest text-pylon-text-secondary outline-none"
          />
        ) : (
          <span
            className="cursor-default truncate font-mono text-xs font-semibold uppercase tracking-widest text-pylon-text-secondary"
            onDoubleClick={() => {
              setEditValue(column.title);
              setEditing(true);
            }}
          >
            {column.title}
          </span>
        )}
        <span className={`shrink-0 font-mono text-xs ${
          column.wipLimit != null && cardCount > column.wipLimit
            ? "text-pylon-danger font-bold"
            : column.wipLimit != null && cardCount === column.wipLimit
              ? "text-[oklch(65%_0.15_70)]"
              : "text-pylon-text-secondary"
        }`}>
          {filteredCount != null ? `${filteredCount} of ` : ""}{cardCount}{column.wipLimit != null ? `/${column.wipLimit}` : ""}
        </span>
      </div>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            size="icon-xs"
            className="shrink-0 text-pylon-text-secondary opacity-0 transition-opacity group-hover/column:opacity-100 focus-visible:opacity-100 hover:text-pylon-text"
            aria-label="Column options"
          >
            <MoreHorizontal className="size-3.5" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem
            onClick={() => {
              setEditValue(column.title);
              setEditing(true);
            }}
          >
            Rename
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => toggleColumnCollapse(column.id)}>
            Collapse
          </DropdownMenuItem>
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>Width</DropdownMenuSubTrigger>
            <DropdownMenuSubContent>
              <DropdownMenuRadioGroup value={column.width} onValueChange={(v) => handleWidthChange(v as ColumnWidth)}>
                <DropdownMenuRadioItem value="narrow">Narrow</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="standard">Standard</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="wide">Wide</DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
            </DropdownMenuSubContent>
          </DropdownMenuSub>
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>Color</DropdownMenuSubTrigger>
            <DropdownMenuSubContent>
              <DropdownMenuCheckboxItem
                checked={column.color == null}
                onSelect={() => setColumnColor(column.id, null)}
              >
                None
              </DropdownMenuCheckboxItem>
              <DropdownMenuSeparator />
              <div className="flex flex-wrap gap-1.5 px-2 py-1.5">
                {COLOR_PRESETS.map(({ hue, label }) => (
                  <button
                    key={hue}
                    onClick={() => setColumnColor(column.id, hue)}
                    className="size-5 rounded-full transition-transform hover:scale-110"
                    style={{
                      backgroundColor: `oklch(55% 0.12 ${hue})`,
                      outline: column.color === hue ? "2px solid currentColor" : "none",
                      outlineOffset: "1px",
                    }}
                    title={label}
                    aria-label={label}
                  />
                ))}
              </div>
            </DropdownMenuSubContent>
          </DropdownMenuSub>
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>WIP Limit</DropdownMenuSubTrigger>
            <DropdownMenuSubContent>
              <DropdownMenuRadioGroup
                value={column.wipLimit?.toString() ?? "none"}
                onValueChange={(v) => setColumnWipLimit(column.id, v === "none" ? null : parseInt(v))}
              >
                <DropdownMenuRadioItem value="none">None</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="3">3</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="5">5</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="7">7</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="10">10</DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
            </DropdownMenuSubContent>
          </DropdownMenuSub>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            variant="destructive"
            onClick={() => deleteColumn(column.id)}
          >
            Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
