"use client";

import React, { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { FiArrowRight, FiCalendar, FiChevronDown } from "react-icons/fi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";
import type { Audit } from "./audit.utils";
import { statusMeta, typeMeta, fullName } from "./audit.utils";

function StandardsBadges({ standards }: { standards: { id: number; name?: string }[] }) {
  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" }}>
      <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 && (
        <React.Fragment>
          <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",
            }}
          >
            {"+" + rest.length}
            <FiChevronDown
              size={10}
              style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 0.15s" }}
            />
          </button>

          {open && pos && (
            <React.Fragment>
              <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", display: "flex", alignItems: "center", gap: 6 }}
                  >
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#4338ca", flexShrink: 0 }} />
                    {s.name}
                  </div>
                ))}
              </div>
            </React.Fragment>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

function Avatar({ name, gradient }: { name?: string; gradient: string }) {
  return (
    <span
      style={{
        width: 22,
        height: 22,
        borderRadius: "50%",
        background: gradient,
        color: "#fff",
        fontSize: 10,
        fontWeight: 700,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        flexShrink: 0,
      }}
    >
      {(name && name[0] ? name[0] : "?").toUpperCase()}
    </span>
  );
}

interface Props {
  audit: Audit;
}

export default function AuditRow({ audit }: Props) {
  const router = useRouter();
  const meta = statusMeta(audit.status, styles);
  const type = typeMeta(audit.audit_type);
  const leadName = fullName(audit.lead_auditor);
  const coCount = (audit.co_auditors || []).length;

  return (
    <tr>
      <td style={{ verticalAlign: "top" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
          <span className={styles.idCell}>{audit.audit_code || "—"}</span>
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              padding: "2px 8px",
              borderRadius: 99,
              background: type.bg,
              color: type.color,
              fontSize: 10,
              fontWeight: 600,
              whiteSpace: "nowrap",
              width: "fit-content",
            }}
          >
            {type.label}
          </span>
        </div>
      </td>
      <td className={styles.nameCell}>{audit.branch?.branchName || "—"}</td>
      <td>{audit.proposed_date ? new Date(audit.proposed_date).toLocaleDateString() : "—"}</td>
      <td>
        <StandardsBadges standards={audit.standards || []} />
      </td>
      <td>
        {leadName ? (
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#374151" }}>
            <Avatar name={leadName} gradient="linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)" />
            <span>{leadName}</span>
            {coCount > 0 && (
              <span
                style={{
                  fontSize: 10,
                  fontWeight: 700,
                  color: "#6b7280",
                  background: "#f3f4f6",
                  border: "1px solid #e5e7eb",
                  borderRadius: 99,
                  padding: "1px 6px",
                }}
                title={(audit.co_auditors || []).map(fullName).join(", ")}
              >
                {"+" + coCount}
              </span>
            )}
          </div>
        ) : (
          "—"
        )}
      </td>
      <td>
        <span className={styles.statusBadge + " " + meta.badgeClass}>
          <span className={styles.statusDot} />
          {meta.label}
        </span>
      </td>
      <td className={styles.actionsCell}>
        <div className={styles.actionGroup}>
          {/* <button
            className={styles.actionBtnView}
            onClick={() => router.push("/client/dashboard/audits/" + audit.id)}
            title="View audit"
          >
            <FiArrowRight size={14} />
          </button> */}
          <button
            onClick={() => router.push("/client/dashboard/audits/" + audit.id)}
            title="View Schedule"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              padding: "7px 15px",
              borderRadius: 9,
              border: "none",
              cursor: "pointer",
              fontSize: 12.5,
              fontWeight: 700,
              color: "#fff",
              background: "linear-gradient(135deg, #7c3aed, #4a0080)",
              boxShadow: "0 8px 18px -10px rgba(74,0,128,0.7)",
              fontFamily: "inherit",
            }}
          >
            View Schedule <FiCalendar size={13} />
          </button>
        </div>
      </td>
    </tr>
  );
}
