"use client";

import React, { useState, useRef, useEffect } from "react";
import { FiEdit2, FiTrash2, FiChevronDown } from "react-icons/fi";
import type {
  ChecklistTemplate,
  ChecklistTemplateItem,
} from "@/lib/api/types/checklist.types";
import {
  TEMPLATE_TYPE_CONFIG,
  templateKind,
} from "@/lib/api/mappers/checklist.mappers";

interface Props {
  row: ChecklistTemplate;
  onEdit: (row: ChecklistTemplate) => void;
  onDelete: (row: ChecklistTemplate) => void;
  isDeleting?: boolean;
  /** Permitted action keys for THIS user on the checklist-templates module */
  permittedActions: Set<string>;
}

// ─── Checklist Items Badge Group ─────────────────────────────────────────────
// Direct adaptation of StandardsBadges from MyAuditRow.tsx: first item as an
// indigo chip, "+N ▾" opens a fixed-position popover listing every item.
function ItemsBadges({ items }: { items: ChecklistTemplateItem[] }) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
  const chipRef = useRef<HTMLButtonElement | null>(null);

  if (!items || items.length === 0) {
    return <span style={{ color: "#9ca3af", fontSize: 12 }}>—</span>;
  }

  const sorted = [...items].sort(
    (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0),
  );
  const first = sorted[0];
  const rest = sorted.slice(1);

  const handleToggle = () => {
    if (!open && chipRef.current) {
      const rect = chipRef.current.getBoundingClientRect();
      setPos({ top: rect.bottom + 4, left: rect.left });
    } else {
      setPos(null);
    }
    setOpen(!open);
  };

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (chipRef.current && !chipRef.current.contains(e.target as Node)) {
        setOpen(false);
        setPos(null);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        flexWrap: "wrap",
        maxWidth: "100%",
      }}
    >
      <span
        title={first.item_text}
        style={{
          display: "inline-flex",
          alignItems: "center",
          padding: "3px 9px",
          borderRadius: 99,
          background: "#eef2ff",
          color: "#4338ca",
          fontSize: 11,
          fontWeight: 600,
          whiteSpace: "nowrap",
          border: "1px solid #c7d2fe",
          maxWidth: 180,
        }}
      >
        <span
          style={{
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {first.item_text}
        </span>
      </span>

      {rest.length > 0 && (
        <>
          <button
            ref={chipRef}
            type="button"
            onClick={handleToggle}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 3,
              padding: "3px 8px",
              borderRadius: 99,
              background: "#f3f4f6",
              color: "#4b5563",
              fontSize: 11,
              fontWeight: 700,
              border: "1px solid #e5e7eb",
              cursor: "pointer",
              whiteSpace: "nowrap",
            }}
            title={rest.map((i) => i.item_text).join(", ")}
          >
            +{rest.length}
            <FiChevronDown
              size={10}
              style={{
                transform: open ? "rotate(180deg)" : "none",
                transition: "transform 0.15s",
              }}
            />
          </button>

          {open && pos && (
            <>
              <div
                onClick={() => {
                  setOpen(false);
                  setPos(null);
                }}
                style={{ position: "fixed", inset: 0, zIndex: 9998 }}
              />
              <div
                style={{
                  position: "fixed",
                  top: pos.top,
                  left: pos.left,
                  zIndex: 9999,
                  background: "#fff",
                  border: "1px solid #e5e7eb",
                  borderRadius: 8,
                  boxShadow: "0 10px 30px rgba(0,0,0,0.12)",
                  padding: "6px",
                  minWidth: 240,
                  maxWidth: 340,
                  maxHeight: 240,
                  overflowY: "auto",
                }}
              >
                <div
                  style={{
                    padding: "4px 8px",
                    fontSize: 10,
                    fontWeight: 700,
                    color: "#6b7280",
                    textTransform: "uppercase",
                    letterSpacing: "0.05em",
                  }}
                >
                  All Items ({sorted.length})
                </div>
                {sorted.map((i) => (
                  <div
                    key={i.id}
                    style={{
                      padding: "6px 8px",
                      fontSize: 12,
                      color: "#374151",
                      borderRadius: 4,
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <span
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: "50%",
                        background: "#4338ca",
                        flexShrink: 0,
                      }}
                    />
                    {i.item_text}
                  </div>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}

// ─── Main Row Component ──────────────────────────────────────────────────────
export default function ChecklistTemplateRow({
  row,
  onEdit,
  onDelete,
  isDeleting,
  permittedActions,
}: Props) {
  const typeMeta = TEMPLATE_TYPE_CONFIG[templateKind(row.is_generic)];

  // ✅ PERMISSION GATING (mirrors MyAuditRow)
  // 'edit'   permission → user can open the template editor
  // 'delete' permission → user can delete the template
  const canEdit =
    permittedActions.has("edit") || permittedActions.has("view-all");
  const canDelete = permittedActions.has("delete");

  return (
    <tr
      style={{
        borderTop: "1px solid #f1f5f9",
        background: "transparent",
        transition: "background 0.15s",
      }}
    >
      {/* 1. Template — name on top, type pill below (audit-code cell layout) */}
      <td style={{ padding: "12px 10px", width: 260, verticalAlign: "top" }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            gap: 5,
          }}
        >
          <span
            style={{
              fontWeight: 600,
              fontSize: 13,
              color: "#111827",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              maxWidth: "100%",
            }}
            title={row.name}
          >
            {row.name}
          </span>
          <span
            style={{
              padding: "2px 8px",
              borderRadius: 99,
              background: typeMeta.bg,
              color: typeMeta.color,
              fontSize: 10,
              fontWeight: 600,
              whiteSpace: "nowrap",
            }}
          >
            {typeMeta.icon} {typeMeta.label}
          </span>
        </div>
      </td>

      {/* 2. Checklist Items — first item chip + "+N" popover */}
      <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
        <ItemsBadges items={row.items ?? []} />
      </td>

      {/* 3. Actions — gated by permittedActions, MyAuditRow button styling */}
      <td style={{ padding: "12px 10px", width: 150, verticalAlign: "top" }}>
        <div style={{ display: "flex", gap: 6 }}>
          {canEdit && (
            <button
              onClick={() => onEdit(row)}
              title="Edit template"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "5px 10px",
                borderRadius: 6,
                border: "1px solid #c7d2fe",
                background: "#eef2ff",
                color: "#4338ca",
                fontSize: 11,
                fontWeight: 600,
                cursor: "pointer",
                whiteSpace: "nowrap",
              }}
            >
              <FiEdit2 size={12} /> Edit
            </button>
          )}

          {canDelete && (
            <button
              onClick={() => onDelete(row)}
              disabled={isDeleting}
              title="Delete template"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "5px 9px",
                borderRadius: 6,
                border: "1px solid #fca5a5",
                background: "#fef2f2",
                color: "#b91c1c",
                fontSize: 11,
                fontWeight: 600,
                cursor: isDeleting ? "not-allowed" : "pointer",
                opacity: isDeleting ? 0.6 : 1,
              }}
            >
              <FiTrash2 size={12} />
            </button>
          )}

          {!canEdit && !canDelete && (
            <span
              style={{ fontSize: 11, color: "#9ca3af", fontStyle: "italic" }}
            >
              —
            </span>
          )}
        </div>
      </td>
    </tr>
  );
}
