"use client";

import React, { useEffect, useState } from "react";
import styles from "../../commonstyle/FormStyles.module.css";
import { getAuditRequest } from "@/lib/api/audit-request.api";
import { getStandards } from "@/lib/api/standard.api";
import {
  formatDate,
  formatDateTime,
  formatTime,
  REQUEST_STATUS_META,
} from "@/lib/api/mappers/audit-request.mappers";
import {
  RequestStatusBadge,
  RequestModeBadge,
  CertificationTypeBadge,
} from "../components/AuditRequestBadges";
import type {
  AuditRequest,
  AuditRequestStatus,
} from "@/lib/api/types/audit-request.types";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  requestId: number | null;
  refreshFlag?: number;
}

interface TimelineEvent {
  status: AuditRequestStatus | "CREATED";
  label: string;
  date: string | null;
  by: string | null;
  icon: string;
  color: string;
}

interface StandardItem {
  id: number;
  name: string;
  title?: string;
}

const fieldLabelStyle: React.CSSProperties = {
  fontSize: 11,
  fontWeight: 600,
  color: "#94a3b8",
  textTransform: "uppercase",
  letterSpacing: "0.5px",
};

export default function AuditRequestDetailModal({
  isOpen,
  onClose,
  requestId,
  refreshFlag = 0,
}: Props) {
  const [request, setRequest] = useState<AuditRequest | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [standardsMap, setStandardsMap] = useState<Record<number, StandardItem>>({});

  useEffect(() => {
    getStandards()
      .then((list: any[]) => {
        const map: Record<number, StandardItem> = {};
        list.forEach((s: any) => { map[s.id] = s; });
        setStandardsMap(map);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (!isOpen || !requestId) return;
    setLoading(true);
    setError(null);
    getAuditRequest(requestId)
      .then((r) => setRequest(r))
      .catch((err) => setError(err?.message || "Failed to load request"))
      .finally(() => setLoading(false));
  }, [isOpen, requestId, refreshFlag]);

  useEffect(() => {
    if (!isOpen) { setRequest(null); setError(null); }
  }, [isOpen]);

  if (!isOpen) return null;

  const getStandardName = (id: number): string => {
    const s = standardsMap[id];
    return s ? (s.name || s.title || `Standard #${id}`) : `Standard #${id}`;
  };

  const documents: any[] = Array.isArray((request as any)?.documents) ? (request as any).documents : [];

  const buildTimeline = (r: AuditRequest): TimelineEvent[] => {
    const events: TimelineEvent[] = [];
    events.push({ status: "SUBMITTED", label: "Request Submitted", date: r.created_at, by: r.requested_by ? `${r.requested_by.firstName} ${r.requested_by.lastName}` : "Marketing", icon: "📤", color: "#4f46e5" });
    if (r.reviewed_at) events.push({ status: "UNDER_REVIEW", label: "Reviewed by Coordinator", date: r.reviewed_at, by: r.reviewed_by ? `${r.reviewed_by.firstName} ${r.reviewed_by.lastName}` : "Coordinator", icon: "👀", color: "#b45309" });
    if (r.status === "SCHEDULED" && r.scheduled_at) events.push({ status: "SCHEDULED", label: `Scheduled · ${r.audit_schedule_row?.audit_code ?? ""}`, date: r.scheduled_at, by: r.reviewed_by ? `${r.reviewed_by.firstName} ${r.reviewed_by.lastName}` : "Coordinator", icon: "✅", color: "#059669" });
    if (r.status === "REJECTED") events.push({ status: "REJECTED", label: "Request Rejected", date: r.reviewed_at ?? r.updated_at, by: r.reviewed_by ? `${r.reviewed_by.firstName} ${r.reviewed_by.lastName}` : "Coordinator", icon: "❌", color: "#dc2626" });
    if (r.status === "CANCELLED") events.push({ status: "CANCELLED", label: "Request Cancelled", date: r.updated_at, by: "—", icon: "🚫", color: "#475569" });
    return events;
  };

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modalContent} onClick={(e) => e.stopPropagation()} style={{ maxWidth: 820, width: "95%", borderRadius: 16, overflow: "hidden" }}>

        {/* ═══ Premium Header ═══ */}
        <div style={{ background: "linear-gradient(135deg, #0c4a6e 0%, #1e40af 50%, #7c3aed 100%)", padding: "28px 32px 24px", position: "relative" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)", fontWeight: 600, letterSpacing: "0.5px", textTransform: "uppercase", marginBottom: 6 }}>Audit Request</div>
              <h2 style={{ fontSize: 22, fontWeight: 700, color: "#fff", margin: 0, fontFamily: "'IBM Plex Mono', monospace" }}>#{requestId}</h2>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {request && <div style={{ marginRight: 8 }}><RequestStatusBadge status={request.status} /></div>}
              <button onClick={onClose} type="button" aria-label="Close" style={{ width: 32, height: 32, borderRadius: 8, background: "rgba(255,255,255,0.15)", border: "none", color: "#fff", fontSize: 16, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>✕</button>
            </div>
          </div>
          {request && (
            <div style={{ display: "flex", gap: 12, marginTop: 16, flexWrap: "wrap" }}>
              <HeaderChip label="Company" value={request.company?.name ?? (request as any).company_name ?? "—"} />
              <HeaderChip label="Auditee" value={request.auditee_name || "—"} />
              {request.audit_schedule_row?.audit_code && <HeaderChip label="Audit Code" value={request.audit_schedule_row.audit_code} mono />}
            </div>
          )}
        </div>

        {loading ? (
          <div style={{ padding: 80, textAlign: "center", color: "#9ca3af", fontSize: 14 }}>Loading request details...</div>
        ) : error ? (
          <div style={{ padding: 80, textAlign: "center", color: "#dc2626", fontSize: 14 }}>⚠️ {error}</div>
        ) : !request ? (
          <div style={{ padding: 80, textAlign: "center", color: "#9ca3af", fontSize: 14 }}>Request not found.</div>
        ) : (
          <div style={{ padding: "24px 32px", maxHeight: "60vh", overflowY: "auto" }}>

            {/* ═══ Client Information ═══ */}
            <SectionTitle icon="👤" title="Client Information" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px", marginBottom: 24 }}>
              <DetailField label="Company" value={request.company?.name ?? "—"} />
              <DetailField label="Auditee Name" value={request.auditee_name} />
              <DetailField label="Contact" value={request.auditee_contact} mono />
              <DetailField label="Email" value={request.auditee_email} mono />
            </div>

            {/* ═══ Audit Scope ═══ */}
            <SectionTitle icon="📋" title="Audit Scope" />
            <div style={{ marginBottom: 24 }}>
              <div style={{ marginBottom: 14 }}>
                <div style={fieldLabelStyle}>Standards</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 6 }}>
                  {request.standard_ids?.length
                    ? request.standard_ids.map((id: number) => (
                        <span key={id} style={{ padding: "4px 12px", borderRadius: 6, background: "linear-gradient(135deg, #eff6ff, #e0e7ff)", border: "1px solid #bfdbfe", fontSize: 12, fontWeight: 600, color: "#1e40af" }}>
                          {getStandardName(id)}
                        </span>
                      ))
                    : <span style={{ fontSize: 13, color: "#9ca3af" }}>—</span>}
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px" }}>
                <div>
                  <div style={fieldLabelStyle}>Certification Type</div>
                  <div style={{ marginTop: 6 }}><CertificationTypeBadge type={request.certification_type} /></div>
                </div>
                <DetailField label="Accreditation" value={request.accreditation} />
              </div>
              {request.scope_of_work && (
                <div style={{ marginTop: 14 }}>
                  <div style={fieldLabelStyle}>Scope of Work</div>
                  <div style={{ fontSize: 13, color: "#1e293b", marginTop: 6, lineHeight: 1.7, padding: "10px 14px", background: "#f8fafc", borderRadius: 8, border: "1px solid #e2e8f0" }}>
                    {request.scope_of_work}
                  </div>
                </div>
              )}
            </div>

            {/* ═══ Proposed Schedule ═══ */}
            <SectionTitle icon="📅" title="Proposed Schedule" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px", marginBottom: 24 }}>
              <DetailField label="Proposed Date" value={formatDate(request.proposed_date)} />
              <DetailField label="Proposed Time" value={formatTime(request.proposed_time)} />
              <DetailField label="Location" value={request.location} />
              <div>
                <div style={fieldLabelStyle}>Mode</div>
                <div style={{ marginTop: 6 }}><RequestModeBadge mode={request.mode} /></div>
              </div>
            </div>

            {/* ═══ Linked Audit ═══ */}
            {request.audit_schedule_row && (
              <>
                <SectionTitle icon="🔗" title="Scheduled Audit" />
                <div style={{ padding: "16px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 10, marginBottom: 24 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px" }}>
                    <DetailField label="Audit Code" value={request.audit_schedule_row.audit_code} mono />
                    <DetailField label="Schedule Date" value={formatDate(request.audit_schedule_row.schedule?.schedule_date ?? null)} />
                    <DetailField label="Audit Time" value={request.audit_schedule_row.audit_time_label ?? "—"} />
                    <DetailField label="Audit Type" value={`${request.audit_schedule_row.audit_type}${request.audit_schedule_row.audit_stage ? ` · ${request.audit_schedule_row.audit_stage}` : ""}`} />
                    <DetailField label="Mode" value={request.audit_schedule_row.audit_mode} />
                    <DetailField label="Lead Auditor" value={request.audit_schedule_row.lead_auditor ? `${request.audit_schedule_row.lead_auditor.firstName} ${request.audit_schedule_row.lead_auditor.lastName}` : "—"} />
                  </div>
                </div>
              </>
            )}

            {/* ═══ Documents ═══ */}
            {documents.length > 0 && (
              <>
                <SectionTitle icon="📎" title="Uploaded Documents" />
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 24 }}>
                  {documents.map((doc: any, idx: number) => {
                    const baseUrl = (process.env.NEXT_PUBLIC_API_URL || "").replace(/\/api\/?$/, "");
                    const docUrl = doc.path ? baseUrl + "/" + doc.path : null;
                    return (
                      <div key={idx} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", border: "1px solid #e2e8f0", borderRadius: 8, background: "#fafbfc" }}>
                        <div style={{ width: 36, height: 36, borderRadius: 8, background: doc.doc_type === "trade_license" ? "#fef3c7" : doc.doc_type === "previous_certificate" ? "#dbeafe" : "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, flexShrink: 0 }}>
                          {doc.doc_type === "trade_license" ? "📜" : doc.doc_type === "previous_certificate" ? "🏆" : "📄"}
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 500, color: "#0f172a", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {doc.filename || doc.originalName || `Document ${idx + 1}`}
                          </div>
                          <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 1 }}>
                            {doc.doc_type === "trade_license" ? "Trade License" : doc.doc_type === "previous_certificate" ? "Previous Certificate" : "Supporting Document"}
                            {doc.size ? ` · ${(doc.size / 1024).toFixed(0)} KB` : ""}
                          </div>
                        </div>
                        {docUrl && (
                          <a href={docUrl} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, color: "#2563eb", textDecoration: "none", fontWeight: 600, padding: "5px 12px", border: "1px solid #bfdbfe", borderRadius: 6, background: "#eff6ff", display: "inline-flex", alignItems: "center", gap: 4 }}>
                            View ↗
                          </a>
                        )}
                      </div>
                    );
                  })}
                </div>
              </>
            )}

            {/* ═══ Remarks ═══ */}
            {(request.marketing_remarks || request.coordinator_remarks) && (
              <>
                <SectionTitle icon="💬" title="Remarks" />
                <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 24 }}>
                  {request.marketing_remarks && (
                    <div style={{ padding: "12px 16px", background: "#fffbeb", borderLeft: "4px solid #f59e0b", borderRadius: "0 8px 8px 0" }}>
                      <div style={{ fontWeight: 700, color: "#92400e", fontSize: 12, marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.3px" }}>Marketing Remarks</div>
                      <div style={{ color: "#78350f", fontSize: 13, lineHeight: 1.6 }}>{request.marketing_remarks}</div>
                    </div>
                  )}
                  {request.coordinator_remarks && (
                    <div style={{ padding: "12px 16px", background: "#eff6ff", borderLeft: "4px solid #3b82f6", borderRadius: "0 8px 8px 0" }}>
                      <div style={{ fontWeight: 700, color: "#1e3a8a", fontSize: 12, marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.3px" }}>Coordinator Notes</div>
                      <div style={{ color: "#1e3a8a", fontSize: 13, lineHeight: 1.6 }}>{request.coordinator_remarks}</div>
                    </div>
                  )}
                </div>
              </>
            )}

            {/* ═══ Rejection ═══ */}
            {request.status === "REJECTED" && request.rejection_reason && (
              <>
                <SectionTitle icon="❌" title="Rejection Details" />
                <div style={{ padding: "12px 16px", background: "#fef2f2", borderLeft: "4px solid #dc2626", borderRadius: "0 8px 8px 0", marginBottom: 24 }}>
                  <div style={{ fontWeight: 700, color: "#991b1b", fontSize: 12, marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.3px" }}>Reason</div>
                  <div style={{ color: "#7f1d1d", fontSize: 13, lineHeight: 1.6 }}>{request.rejection_reason}</div>
                </div>
              </>
            )}

            {/* ═══ Status Timeline ═══ */}
            <SectionTitle icon="🕒" title="Status Timeline" />
            <div style={{ paddingLeft: 4, marginBottom: 8 }}>
              {buildTimeline(request).map((event, idx, arr) => (
                <div key={idx} style={{ display: "flex", gap: 14, position: "relative", paddingBottom: idx < arr.length - 1 ? 20 : 0 }}>
                  {idx < arr.length - 1 && <div style={{ position: "absolute", left: 15, top: 34, bottom: 0, width: 2, background: "#e2e8f0" }} />}
                  <div style={{ width: 32, height: 32, borderRadius: "50%", background: event.color, display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontSize: 14, flexShrink: 0, zIndex: 1, boxShadow: `0 2px 6px ${event.color}40` }}>
                    {event.icon}
                  </div>
                  <div style={{ flex: 1, paddingTop: 4 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "#0f172a" }}>{event.label}</div>
                    <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 2 }}>
                      {event.date ? formatDateTime(event.date) : "—"} {event.by && `· by ${event.by}`}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ═══ Footer ═══ */}
        <div style={{ padding: "14px 32px", borderTop: "1px solid #e2e8f0", display: "flex", justifyContent: "flex-end", gap: 10, background: "#fafbfc" }}>
          <button type="button" onClick={onClose} style={{ padding: "8px 24px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 13, fontWeight: 600, color: "#475569", cursor: "pointer" }}>
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// Helper Components
// ═══════════════════════════════════════════════════════════════════════════

function SectionTitle({ icon, title }: { icon: string; title: string }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14, paddingBottom: 8, borderBottom: "1px solid #f1f5f9" }}>
      <span style={{ fontSize: 15 }}>{icon}</span>
      <span style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", textTransform: "uppercase", letterSpacing: "0.5px" }}>{title}</span>
    </div>
  );
}

function HeaderChip({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
  return (
    <div style={{ padding: "6px 14px", borderRadius: 8, background: "rgba(255,255,255,0.12)", backdropFilter: "blur(8px)" }}>
      <div style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.5px" }}>{label}</div>
      <div style={{ fontSize: 13, color: "#fff", fontWeight: 600, marginTop: 2, fontFamily: mono ? "'IBM Plex Mono', monospace" : "inherit", maxWidth: 220, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{value}</div>
    </div>
  );
}

function DetailField({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
  return (
    <div style={{ marginBottom: 4 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "#94a3b8", textTransform: "uppercase", letterSpacing: "0.5px" }}>{label}</div>
      <div style={{ fontSize: 13, color: "#1e293b", marginTop: 4, fontWeight: 500, fontFamily: mono ? "'IBM Plex Mono', monospace" : undefined }}>{value || "—"}</div>
    </div>
  );
}