"use client";

import React, { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { FiArrowRight, FiCheck, FiEye, FiChevronDown } from "react-icons/fi";
import type { MyAuditRow, StandardRef } from "@/lib/api/types/my-audits.types";
import {
  STATUS_CONFIG,
  TYPE_CONFIG,
  formatUserName,
  formatDateWithHint,
} from "@/lib/api/mappers/my-audits.mappers";

interface Props {
  row: MyAuditRow;
  onOpen: (row: MyAuditRow) => void;
  onMarkComplete: (row: MyAuditRow) => void;
  isCompleting?: boolean;
  /** Permitted action keys for THIS user on the my-audits module */
  permittedActions: Set<string>;
}

// ─── Standards Badge Group ───────────────────────────────────────────────────
function StandardsBadges({ standards }: { standards: StandardRef[] }) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
  const chipRef = useRef<HTMLButtonElement | null>(null);

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

  const first = standards[0];
  const rest = standards.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
        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",
        }}
      >
        {first.name}
      </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((s) => s.name).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: 200,
                  maxHeight: 240,
                  overflowY: "auto",
                }}
              >
                <div
                  style={{
                    padding: "4px 8px",
                    fontSize: 10,
                    fontWeight: 700,
                    color: "#6b7280",
                    textTransform: "uppercase",
                    letterSpacing: "0.05em",
                  }}
                >
                  All Standards ({standards.length})
                </div>
                {standards.map((s) => (
                  <div
                    key={s.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,
                      }}
                    />
                    {s.name}
                  </div>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}

// ─── Main Row Component ──────────────────────────────────────────────────────
export default function MyAuditRowComponent({
  row,
  onOpen,
  onMarkComplete,
  isCompleting,
  permittedActions,
}: Props) {
  const router = useRouter();
  // 🆕 If this audit was reassigned away from the current viewer during a
  // reschedule, always show "Rescheduled" here — regardless of the row's
  // real (shared) status, which has already reset to PENDING for whoever
  // it's now assigned to.
  const status = row.reassigned_from_you
    ? STATUS_CONFIG.RESCHEDULED
    : STATUS_CONFIG[row.status];
  const typeMeta = TYPE_CONFIG[row.audit_type];

  const dateInfo = row.schedule?.schedule_date
    ? formatDateWithHint(row.schedule.schedule_date)
    : { display: "—" };

  const isToday = dateInfo.hint === "Today";
  const isCompleted = row.status === "COMPLETED";
  const isCancelled = row.status === "CANCELLED";

  // ✅ PERMISSION GATING
  // 'view' permission → user can Open the workspace
  // 'complete' permission → user can mark audits complete
  const canView =
    permittedActions.has("view") || permittedActions.has("view-all");
  const canComplete =
    permittedActions.has("complete") && !isCompleted && !isCancelled;

  return (
    <tr
      style={{
        borderTop: "1px solid #f1f5f9",
        background: isToday ? "#f0fdfa" : "transparent",
        opacity: isCompleted ? 0.75 : 1,
        transition: "background 0.15s",
      }}
    >
      {/* 1. Audit Code */}
      <td style={{ padding: "12px 10px", width: 170, verticalAlign: "top" }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            gap: 5,
          }}
        >
          <a
            href={`/modules/audits/${row.id}`}
            onClick={(e) => {
              e.preventDefault();
              if (canView) router.push(`/modules/audits/${row.id}`);
            }}
            style={{
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 11,
              color: canView ? "#0f766e" : "#9ca3af",
              fontWeight: 600,
              textDecoration: "none",
              whiteSpace: "nowrap",
              cursor: canView ? "pointer" : "not-allowed",
            }}
          >
            {row.audit_code}
          </a>
          <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. Company */}
      <td style={{ padding: "12px 10px", width: 220, verticalAlign: "top" }}>
        <div
          style={{
            fontWeight: 600,
            fontSize: 13,
            color: "#111827",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
          title={row.company?.name ?? ""}
        >
          {row.company?.name ?? "—"}
        </div>
        {row.company?.contact_person && (
          <div style={{ fontSize: 11, color: "#6b7280", marginTop: 2 }}>
            {row.company.contact_person}
            {row.company.mobile ? ` · ${row.company.mobile}` : ""}
          </div>
        )}
      </td>

      {/* 3. Date / Time */}
      <td style={{ padding: "12px 10px", width: 150, verticalAlign: "top" }}>
        <div
          style={{
            fontSize: 13,
            color: "#111827",
            display: "flex",
            alignItems: "center",
            gap: 6,
          }}
        >
          {dateInfo.display}
          {dateInfo.hint && (
            <span
              style={{
                fontSize: 10,
                fontWeight: 700,
                padding: "1px 6px",
                borderRadius: 99,
                background: isToday ? "#0f766e" : "#f3f4f6",
                color: isToday ? "#fff" : dateInfo.hintColor || "#6b7280",
              }}
            >
              {dateInfo.hint}
            </span>
          )}
        </div>
        <div style={{ fontSize: 11, color: "#6b7280", marginTop: 2 }}>
          {row.audit_time_label || row.audit_time || "—"}
          {row.audit_mode ? ` · ${row.audit_mode}` : ""}
        </div>
      </td>

      {/* 4. Standards */}
      <td style={{ padding: "12px 10px", width: 170, verticalAlign: "top" }}>
        <StandardsBadges standards={row.standards ?? []} />
      </td>

      {/* 5. Coordinator */}
      <td
        style={{
          padding: "12px 10px",
          width: 120,
          fontSize: 12,
          color: "#374151",
          verticalAlign: "top",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span
            style={{
              width: 22,
              height: 22,
              borderRadius: "50%",
              background: "linear-gradient(135deg, #7c3aed 0%, #a855f7 100%)",
              color: "#fff",
              fontSize: 10,
              fontWeight: 700,
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            {(row.schedule?.coordinator?.firstName?.[0] ?? "?").toUpperCase()}
          </span>
          <span
            style={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
            title={formatUserName(row.schedule?.coordinator)}
          >
            {formatUserName(row.schedule?.coordinator)}
          </span>
        </div>
      </td>

      {/* 6. Lead Auditor */}
      <td
        style={{
          padding: "12px 10px",
          width: 120,
          fontSize: 12,
          color: "#374151",
          verticalAlign: "top",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span
            style={{
              width: 22,
              height: 22,
              borderRadius: "50%",
              background: "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
              color: "#fff",
              fontSize: 10,
              fontWeight: 700,
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            {(row.lead_auditor?.firstName?.[0] ?? "?").toUpperCase()}
          </span>
          <span
            style={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
            title={formatUserName(row.lead_auditor)}
          >
            {formatUserName(row.lead_auditor)}
          </span>
        </div>
        {row.reassigned_from_you && (
          <div
            style={{
              fontSize: 10,
              color: "#0e7490",
              marginTop: 2,
            }}
          >
            Reassigned to {formatUserName(row.lead_auditor)}
          </div>
        )}
      </td>

      {/* 6.5 Co-Auditor(s) — 🆕 */}
      <td
        style={{
          padding: "12px 10px",
          width: 130,
          fontSize: 12,
          color: "#374151",
          verticalAlign: "top",
        }}
      >
        {row.co_auditors && row.co_auditors.length > 0 ? (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
            {row.co_auditors.map((u) => (
              <span
                key={u.id}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  padding: "2px 8px",
                  borderRadius: 99,
                  fontSize: 10,
                  fontWeight: 600,
                  background: "#f0fdfa",
                  color: "#0f766e",
                  border: "1px solid #99f6e4",
                  whiteSpace: "nowrap",
                }}
                title={formatUserName(u)}
              >
                {formatUserName(u)}
              </span>
            ))}
          </div>
        ) : (
          <span style={{ color: "#9ca3af" }}>—</span>
        )}
      </td>

      {/* 7. Status */}
      <td style={{ padding: "12px 10px", width: 100, verticalAlign: "top" }}>
        <span
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 4,
            padding: "4px 10px",
            borderRadius: 99,
            background: status.bg,
            color: status.text,
            fontSize: 11,
            fontWeight: 600,
            whiteSpace: "nowrap",
          }}
        >
          <span
            style={{
              width: 6,
              height: 6,
              borderRadius: "50%",
              background: status.dot,
            }}
          />
          {status.label}
        </span>
      </td>

      {/* 8. Actions — gated by permittedActions */}
      <td style={{ padding: "12px 10px", width: 120, verticalAlign: "top" }}>
        <div style={{ display: "flex", gap: 6 }}>
          {canView && (
            <button
              onClick={() => onOpen(row)}
              title={isCompleted ? "View" : "Open audit workspace"}
              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",
              }}
            >
              {isCompleted ? (
                <>
                  <FiEye size={12} /> View
                </>
              ) : (
                <>
                  <FiArrowRight size={12} /> View Data
                </>
              )}
            </button>
          )}

          {canComplete && (
            <button
              onClick={() => onMarkComplete(row)}
              disabled={isCompleting}
              title="Mark complete"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "5px 9px",
                borderRadius: 6,
                border: "1px solid #86efac",
                background: "#f0fdf4",
                color: "#166534",
                fontSize: 11,
                fontWeight: 600,
                cursor: isCompleting ? "not-allowed" : "pointer",
                opacity: isCompleting ? 0.6 : 1,
              }}
            >
              <FiCheck size={12} />
            </button>
          )}
          {/* 🆕 Raise NC button */}
          <button
            onClick={() =>
              router.push(`/modules/previous-nc/raise?audit_id=${row.id}`)
            }
            title="Raise a new NC for this audit"
            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: "pointer",
              whiteSpace: "nowrap",
            }}
          >
            + NC
          </button>
          {!canView && !canComplete && (
            <span
              style={{ fontSize: 11, color: "#9ca3af", fontStyle: "italic" }}
            >
              —
            </span>
          )}
        </div>
      </td>
    </tr>
  );
}
