"use client";

import React, { useEffect, useRef, useState } from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiEye,
  FiEdit,
  FiCheckCircle,
  FiXCircle,
  FiCalendar,
  FiTrash2,
  FiArrowRightCircle,
  FiLink,
  FiChevronDown,
} from "react-icons/fi";
import {
  RequestStatusBadge,
  RequestModeBadge,
  CertificationTypeBadge,
} from "./../audit-requests/components/AuditRequestBadges";
import {
  formatDate,
  formatTime,
  canEditRequest,
  canScheduleRequest,
  canRejectRequest,
  canProceedRequest,
} from "@/lib/api/mappers/audit-request.mappers";
import type { AuditRequestTableRow } from "@/lib/api/types/audit-request.types";
// ✅ NEW — split-button action dropdown for the Req column
import AuditRequestActionButton from "./AuditRequestActionButton";

interface Props {
  row: AuditRequestTableRow;
  isSelected: boolean;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onView: (row: AuditRequestTableRow) => void;
  onEdit: (row: AuditRequestTableRow) => void;
  onSchedule: (row: AuditRequestTableRow) => void;
  onReject: (row: AuditRequestTableRow) => void;
  // ✅ NEW — delete handler. Passed down from AuditRequestTable.
  onDelete: (row: AuditRequestTableRow) => void;
  // 🆕 Proceed to Inquiry — opens the pre-filled popup for this request.
  onProceed: (row: AuditRequestTableRow) => void;
  // Permissions/role gates passed down from table.
  // ⚠️ canEdit / canScheduleAction are KEPT (still passed by the table and
  // forwarded to the action dropdown for compatibility) but are NO LONGER
  // used to decide which buttons show — see the gate below.
  canEdit: boolean;
  canScheduleAction: boolean;

  // ✅ permission gating. Set of action keys the user is allowed to use on
  // the 'audit-requests' module. This is now the SINGLE source of truth for
  // which actions show — same as the Inquiry dynamic row.
  permittedActions: Set<string>;
  // 🆕 Standards lookup (id → name) — provided by the table so every row can
  // render real standard badges without its own fetch.
  standardsMap?: Record<number, string>;
}

// ─── 🆕 Standards Badge Group — SAME design as My Audits ─────────────────────
// First pill + "+N" popover listing all standards.
function StandardsBadges({
  ids,
  standardsMap,
}: {
  ids: number[];
  standardsMap: Record<number, string>;
}) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
  const chipRef = useRef<HTMLButtonElement | null>(null);

  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]);

  const names = (ids ?? []).map((id) => ({
    id,
    name: standardsMap[id] ?? `Standard #${id}`,
  }));
  if (!names.length) {
    return <span style={{ color: "#9ca3af", fontSize: 12 }}>—</span>;
  }
  const first = names[0];
  const rest = names.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);
  };

  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((st) => st.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 ({names.length})
                </div>
                {names.map((st) => (
                  <div
                    key={st.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,
                      }}
                    />
                    {st.name}
                  </div>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}

export function AuditRequestRow({
  row,
  isSelected,
  handleRowSelect,
  onView,
  onEdit,
  onSchedule,
  onReject,
  onDelete,
  onProceed,
  canEdit,
  canScheduleAction,
  permittedActions,
  standardsMap = {},
}: Props) {
  // Visual hint for date proximity (matches audit-schedules pattern)
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const pd = new Date(row.proposed_date);
  const dayDiff = Math.round((pd.getTime() - today.getTime()) / 86_400_000);
  const dateHint =
    dayDiff === 0
      ? "🔥 Today"
      : dayDiff === 1
        ? "📍 Tomorrow"
        : dayDiff > 0 && dayDiff <= 7
          ? `🗓️ in ${dayDiff}d`
          : dayDiff < 0
            ? `🕰️ ${Math.abs(dayDiff)}d ago`
            : "";

  // ✅ FIXED — visibility is now driven PURELY by the dynamic permission
  // ✅ NEW — a request is "pending schedule" while it's still SUBMITTED or
  // UNDER_REVIEW (coordinator hasn't created the audit row / assigned auditor yet)
  const needsScheduling =
    row.status === "SUBMITTED" || row.status === "UNDER_REVIEW";

  // ✅ NEW — amber tint applied PER-CELL so it can't be hidden by any td
  // background coming from the CSS module. Selection still takes priority.
  const pendingCellStyle: React.CSSProperties =
    needsScheduling && !isSelected ? { background: "#fff7ed" } : {};

  // ✅ FIXED — visibility is now driven PURELY by the dynamic permission
  const showEdit = row.status !== "COMPLETED";
  const showSchedule =
    permittedActions.has("schedule") && canScheduleRequest(row.status);
  const showReject =
    permittedActions.has("reject") && canRejectRequest(row.status);

  // ✅ NEW — Delete button visibility.

  const showDelete =
    permittedActions.has("delete") && row.status !== "COMPLETED";

  // 🆕 Proceed to Inquiry — enabled while not rejected/cancelled and not yet
  // linked. Uses the 'proceed' permission when configured, otherwise falls
  // back to 'create' (submitting an inquiry is a create-type action).
  const showProceed =
    (permittedActions.has("proceed") || permittedActions.has("create")) &&
    canProceedRequest(row.status, row.inquiry_id);
  const alreadyProceeded = !!row.inquiry_id;


  // once the actions show correctly.
  if (typeof window !== "undefined" && row.sno === 1) {
    console.log(
      "[AUDIT-REQ] permittedActions →",
      Array.from(permittedActions),
      "| first-row flags →",
      { status: row.status, showEdit, showSchedule, showReject, showDelete, needsScheduling },
    );
  }

  return (
    <tr
      className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""}`}
      style={
        needsScheduling && !isSelected
          ? { borderLeft: "4px solid #f59e0b" } // amber stripe on the left
          : undefined
      }
    >
      {/* Select checkbox */}
      <td style={{ textAlign: "center", padding: "10px 8px", ...pendingCellStyle }}>
        <input
          type="checkbox"
          className={styles.checkbox}
          checked={isSelected}
          onChange={(e) => handleRowSelect(row.sno, e.target.checked)}
        />
      </td>

      {/* Request ID + ✅ action dropdown */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            flexWrap: "wrap",
          }}
        >
          <button
            onClick={() => onView(row)}
            style={{
              padding: "4px 10px",
              borderRadius: 12,
              border: "1px solid #c4b5fd",
              background: "#f5f3ff",
              color: "#6d28d9",
              fontSize: 12,
              fontWeight: 700,
              cursor: "pointer",
              fontFamily: "'IBM Plex Mono', monospace",
            }}
            title="View request detail"
          >
            #{row.id}
          </button>

          {/* ✅ split-button action dropdown. Lists every action the user is
              allowed to take on this request (View / Edit / Schedule /
              Reject), gated purely by permittedActions + status rules. */}
          <AuditRequestActionButton
            row={row}
            status={row.status}
            canEdit={canEdit}
            canScheduleAction={canScheduleAction}
            permittedActions={permittedActions}
            onView={onView}
            onEdit={onEdit}
            onSchedule={onSchedule}
            onReject={onReject}
          />
        </div>
      </td>

      {/* Company + auditee */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <div style={{ fontWeight: 700, fontSize: 13, color: "#0f172a" }}>
          {row.company_name}
        </div>
        <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>
          👤 {row.auditee_name}
        </div>
      </td>

      {/* Certification + accreditation */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <CertificationTypeBadge type={row.certification_type} />
      </td>

      {/* 🆕 Standards — real badges (first + "+N" popover, My Audits style) */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <StandardsBadges
          ids={row.raw?.standard_ids ?? []}
          standardsMap={standardsMap}
        />
      </td>

      {/* Proposed date + time */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <div style={{ fontWeight: 600, fontSize: 13, color: "#0f172a" }}>
          {formatDate(row.proposed_date)}
        </div>
        <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>
          🕐 {formatTime(row.proposed_time)}
        </div>
        {dateHint && (
          <div style={{ fontSize: 10, color: "#9ca3af", marginTop: 2 }}>
            {dateHint}
          </div>
        )}
      </td>

      {/* Mode */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <RequestModeBadge mode={row.mode} />
      </td>

      {/* Requested by */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <div style={{ fontWeight: 500, fontSize: 13 }}>
          {row.requested_by_name}
        </div>
        <div style={{ fontSize: 11, color: "#9ca3af" }}>
          {row.requested_by_email}
        </div>
      </td>

      {/* ✅ Lead Auditor. "N/A" until the coordinator schedules the request
          (no linked audit_schedule_row yet); once scheduled, shows the
          assigned auditor's name. */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        {row.lead_auditor_name && row.lead_auditor_name !== "N/A" ? (
          <div style={{ fontWeight: 600, fontSize: 13, color: "#0f172a" }}>
            🧑‍💼 {row.lead_auditor_name}
          </div>
        ) : (
          <span
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: "#9ca3af",
              fontStyle: "italic",
            }}
            title="No auditor assigned yet — set when the coordinator schedules"
          >
            N/A
          </span>
        )}
      </td>

      {/* Status */}
      <td className={styles.nameCell} style={pendingCellStyle}>
        <RequestStatusBadge status={row.status} />
        {/* ✅ NEW — pending-schedule marker for unscheduled requests */}
        {needsScheduling && (
          <div
            style={{
              marginTop: 4,
              fontSize: 11,
              fontWeight: 700,
              color: "#b45309",
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
            }}
            title="Submitted — waiting for the coordinator to schedule and assign an auditor"
          >
            ⏳ Pending Schedule
          </div>
        )}
        {row.status === "SCHEDULED" && row.audit_code !== "—" && (
          <div
            style={{
              marginTop: 4,
              fontSize: 11,
              fontFamily: "'IBM Plex Mono', monospace",
              color: "#0e7490",
              fontWeight: 600,
            }}
            title="Linked audit code"
          >
            🔗 {row.audit_code}
          </div>
        )}
        {/* 🆕 Proceed to Inquiry — linked inquiry badge */}
        {alreadyProceeded && (
          <div
            style={{
              marginTop: 4,
              fontSize: 11,
              fontFamily: "'IBM Plex Mono', monospace",
              fontWeight: 700,
              color: "#0f766e",
              background: "#ccfbf1",
              border: "1px solid #5eead4",
              borderRadius: 10,
              padding: "2px 8px",
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
            }}
            title={`Proceeded to inquiry #${row.inquiry_id}`}
          >
            <FiLink size={10} /> INQ #{row.inquiry_id}
          </div>
        )}
      </td>

      {/* Actions */}
      <td className={styles.actionsCell} style={pendingCellStyle}>
        <div className={styles.actionGroup}>
          {/* View - always available (page loaded ⇒ can view) */}
          <button
            className={styles.actionBtnView}
            onClick={() => onView(row)}
            title="View request details"
          >
            <FiEye size={14} />
          </button>

          {/* Schedule - shown when 'schedule' permission + status allows */}
          {showSchedule && (
            <button
              className={styles.actionBtnView}
              onClick={() => onSchedule(row)}
              title="Schedule this audit (creates audit_schedule_row)"
              style={{
                background: "#dcfce7",
                borderColor: "#86efac",
                color: "#166534",
              }}
            >
              <FiCalendar size={14} />
            </button>
          )}

          {/* 🆕 Proceed to Inquiry — creates the inquiry (proceedings) from
              this request. Disabled look once linked (badge shows instead). */}
          {showProceed && (
            <button
              className={styles.actionBtnView}
              onClick={() => onProceed(row)}
              title="Proceed to Inquiry — creates an inquiry pre-filled from this request"
              style={{
                background: "#ccfbf1",
                borderColor: "#5eead4",
                color: "#0f766e",
              }}
            >
              <FiArrowRightCircle size={14} />
            </button>
          )}
          {alreadyProceeded && (
            <span
              title={`Already proceeded — inquiry #${row.inquiry_id} linked`}
              style={{
                color: "#0f766e",
                fontSize: 16,
                display: "inline-flex",
                alignItems: "center",
                opacity: 0.7,
              }}
            >
              <FiCheckCircle />
            </span>
          )}

          {/* Reject - shown when 'reject' permission + status allows */}
          {showReject && (
            <button
              className={styles.actionBtnView}
              onClick={() => onReject(row)}
              title="Reject this request"
              style={{
                background: "#fef2f2",
                borderColor: "#fca5a5",
                color: "#b91c1c",
              }}
            >
              <FiXCircle size={14} />
            </button>
          )}

          {/* Edit - shown when 'edit' permission + status allows */}
          {showEdit && (
            <button
              className={styles.actionBtnEdit}
              onClick={() => onEdit(row)}
              title="Edit request"
            >
              <FiEdit size={14} />
            </button>
          )}

          {/* ✅ NEW — Delete - shown when 'delete' permission + status is not
              Completed. The backend additionally protects SCHEDULED requests
              (linked to a real audit) and returns a clear message. */}
          {showDelete && (
            <button
              className={styles.actionBtnDelete}
              onClick={() => onDelete(row)}
              title="Delete this request"
            >
              <FiTrash2 size={14} />
            </button>
          )}

          {/* Visual indicator that the request has been linked to an audit row */}
          {row.audit_schedule_row_id && row.status === "SCHEDULED" && (
            <span
              title="Successfully scheduled — audit row created in audit-schedules"
              style={{
                color: "#16a34a",
                fontSize: 16,
                display: "inline-flex",
                alignItems: "center",
              }}
            >
              <FiCheckCircle />
            </span>
          )}
        </div>
      </td>
    </tr>
  );
}