"use client";

import React from "react";
import styles from "../../commonstyle/FormStyles.module.css";
import {
  STATUS_CONFIG,
  TYPE_CONFIG,
  formatDisplayDate,
} from "@/lib/api/mappers/inquiry.mappers";
import { getDraftPdfUrl, getDraftDocxUrl } from "@/lib/api/inquiry.api";
import type { InquiryRow } from "@/lib/api/types/inquiry.types";

// ─── Props ────────────────────────────────────────────────────────────────────
interface Props {
  row: InquiryRow | null;
  onClose: () => void;
  // ✅ NEW — Optional action callbacks (workflow buttons)
  onEdit?: (row: InquiryRow) => void;
  onGenerate?: (row: InquiryRow) => void;
  onConfirm?: (row: InquiryRow) => void;
  onRequestChanges?: (row: InquiryRow) => void;
  onDelete?: (row: InquiryRow) => void;
  generating?: boolean;
}

// ✅ NEW — Document attachment shape
interface InquiryDocument {
  type: string;
  path: string;
  filename: string;
  uploaded_at: string;
  uploaded_by?: number;
}

// ✅ NEW — Document type label map
const DOC_TYPE_LABELS: Record<string, string> = {
  trade_license: "📄 Trade License",
  previous_certificate: "🎫 Previous Certificate",
  audit_report: "📋 Audit Report",
  scope_letter: "✉️ Scope Letter",
  other: "📎 Other",
};

const docTypeLabel = (t: string) => DOC_TYPE_LABELS[t] ?? t;

// ✅ NEW — Open uploaded document in new tab
function openDocument(docPath: string) {
  const apiBase =
    process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, "") ??
    "http://localhost:3007";
  const url = `${apiBase}/${docPath}`;
  window.open(url, "_blank");
}

// ✅ NEW — Authenticated draft download (JWT header required)
async function downloadDraftFile(
  inquiryId: number,
  type: "pdf" | "docx",
  inquiryRef: string,
) {
  try {
    const token = localStorage.getItem("access_token");
    if (!token) {
      alert("You are not logged in. Please refresh and log in again.");
      return;
    }

    const url =
      type === "pdf" ? getDraftPdfUrl(inquiryId) : getDraftDocxUrl(inquiryId);

    const res = await fetch(url, {
      headers: { Authorization: `Bearer ${token}` },
    });

    if (!res.ok) {
      throw new Error(`Download failed: HTTP ${res.status}`);
    }

    const blob = await res.blob();
    const blobUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = blobUrl;
    a.download = `${inquiryRef}_DRAFT.${type}`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(blobUrl);
  } catch (err) {
    console.error("Draft download failed:", err);
    alert("Failed to download. Please try again.");
  }
}

// ─── Small helpers ────────────────────────────────────────────────────────────
function SectionHeader({ title }: { title: string }) {
  return (
    <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
      <span className={styles.sectionDot} />
      {title}
    </div>
  );
}

function Field({
  label,
  value,
  mono = false,
  fullWidth = false,
}: {
  label: string;
  value?: string | null;
  mono?: boolean;
  fullWidth?: boolean;
}) {
  return (
    <div
      className={
        fullWidth ? `${styles.formGroup} ${styles.full}` : styles.formGroup
      }
    >
      <label className={styles.label}>{label}</label>
      <div
        style={{
          padding: "8px 12px",
          borderRadius: 8,
          border: "1px solid #e5e7eb",
          backgroundColor: "#f9fafb",
          fontSize: 13,
          color: value ? "#0f172a" : "#9ca3af",
          fontFamily: mono ? "monospace" : "inherit",
          minHeight: 36,
          lineHeight: 1.5,
        }}
      >
        {value || "—"}
      </div>
    </div>
  );
}

// ✅ NEW — Custom field renderer for badge-style values (cert_body + audit_stage)
function BadgeField({
  label,
  children,
  fullWidth = false,
}: {
  label: string;
  children: React.ReactNode;
  fullWidth?: boolean;
}) {
  return (
    <div
      className={
        fullWidth ? `${styles.formGroup} ${styles.full}` : styles.formGroup
      }
    >
      <label className={styles.label}>{label}</label>
      <div
        style={{
          padding: "8px 12px",
          borderRadius: 8,
          border: "1px solid #e5e7eb",
          backgroundColor: "#f9fafb",
          fontSize: 13,
          minHeight: 36,
          display: "flex",
          alignItems: "center",
          lineHeight: 1.5,
        }}
      >
        {children}
      </div>
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function InquiryViewModal({
  row,
  onClose,
  onEdit,
  onGenerate,
  onConfirm,
  onRequestChanges,
  onDelete,
  generating,
}: Props) {
  if (!row) return null;

  const statusCfg = STATUS_CONFIG[row.status] ?? {
    label: row.status,
    bg: "#f3f4f6",
    color: "#6b7280",
    dot: "#9ca3af",
  };
  const typeCfg = TYPE_CONFIG[row.inquiry_type] ?? {
    label: row.inquiry_type,
    bg: "#f3f4f6",
    color: "#6b7280",
  };

  const submittedBy = row.submitted_by
    ? `${row.submitted_by.firstName} ${row.submitted_by.lastName}`.trim()
    : "—";
  const assignedTo = row.assigned_to
    ? `${row.assigned_to.firstName} ${row.assigned_to.lastName}`.trim()
    : "Unassigned";

  // ✅ NEW — Read documents off the row safely
  const documents: InquiryDocument[] = ((row as any).documents ??
    []) as InquiryDocument[];

  // ✅ NEW — Read cert_body and audit_stage off the row safely
  const certBody = (row as any).cert_body as string | null | undefined;
  const auditStage = (row as any).audit_stage as string | null | undefined;

  // ✅ NEW — Workflow visibility flags
  const hasDraft = !!(row.draft_pdf_path || row.draft_docx_path);
  const showGenerate =
    !!onGenerate &&
    (row.status === "IN_REVIEW" || row.status === "CHANGES_REQUESTED");
  const showConfirm = !!onConfirm && row.status === "DRAFT_READY";
  const showRequestChanges = !!onRequestChanges && row.status === "DRAFT_READY";

  // ✅ Action button base style
  const actionBtnStyle: React.CSSProperties = {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "8px 14px",
    borderRadius: 8,
    fontSize: 12,
    fontWeight: 600,
    cursor: "pointer",
    border: "none",
    transition: "all 0.15s",
    whiteSpace: "nowrap",
  };

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 760 }}
      >
        {/* ── Header ──────────────────────────────────────────────── */}
        <div
          className={styles.modalHeader}
          style={{
            background: "linear-gradient(135deg, #0f766e 0%, #0891b2 100%)",
          }}
        >
          <div>
            <p
              className={styles.modalSubtitle}
              style={{ color: "rgba(255,255,255,0.7)", marginBottom: 2 }}
            >
              Inquiry Details
            </p>
            <h2
              className={styles.modalTitle}
              style={{ color: "#fff", fontFamily: "monospace" }}
            >
              {row.inquiry_ref}
            </h2>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            {/* Type badge */}
            <span
              style={{
                padding: "4px 12px",
                borderRadius: 99,
                fontSize: 11,
                fontWeight: 700,
                backgroundColor: "rgba(255,255,255,0.2)",
                color: "#fff",
              }}
            >
              {typeCfg.label}
            </span>

            {/* ✅ NEW — Cert Body badge in header (if present) */}
            {certBody && (
              <span
                style={{
                  padding: "4px 12px",
                  borderRadius: 99,
                  fontSize: 11,
                  fontWeight: 700,
                  backgroundColor: "rgba(255,255,255,0.25)",
                  color: "#fff",
                  border: "1px solid rgba(255,255,255,0.3)",
                }}
              >
                {certBody === "QRS" ? "🏢 QRS" : "🏛 TQS"}
              </span>
            )}

            <button
              className={styles.closeBtn}
              onClick={onClose}
              type="button"
              style={{
                color: "#fff",
                background: "rgba(255,255,255,0.2)",
                border: "none",
              }}
            >
              ✕
            </button>
          </div>
        </div>

        {/* ── Status strip ────────────────────────────────────────── */}
        <div
          style={{
            padding: "8px 24px",
            backgroundColor: statusCfg.bg,
            borderBottom: "1px solid #e2e8f0",
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <span
            style={{
              width: 8,
              height: 8,
              borderRadius: "50%",
              backgroundColor: statusCfg.dot,
              display: "inline-block",
            }}
          />
          <span
            style={{ fontSize: 12, fontWeight: 700, color: statusCfg.color }}
          >
            {statusCfg.label}
          </span>
          {row.company_name && (
            <>
              <span style={{ color: "#cbd5e1", fontSize: 12 }}>·</span>
              <span style={{ fontSize: 12, color: "#64748b", fontWeight: 500 }}>
                {row.company_name}
              </span>
            </>
          )}

          {/* ✅ NEW — Audit stage chip in status strip (if present) */}
          {auditStage && (
            <>
              <span style={{ color: "#cbd5e1", fontSize: 12 }}>·</span>
              <span
                style={{
                  padding: "2px 10px",
                  borderRadius: 8,
                  fontSize: 11,
                  fontWeight: 600,
                  backgroundColor: "#f5f3ff",
                  color: "#6d28d9",
                  border: "1px solid #ddd6fe",
                }}
              >
                🎯 {auditStage}
              </span>
            </>
          )}
        </div>

        {/* ✅ NEW — ACTION BUTTONS BAR (TOP) ────────────────────────────── */}
        {(onEdit ||
          showGenerate ||
          showConfirm ||
          showRequestChanges ||
          hasDraft ||
          onDelete) && (
          <div
            style={{
              padding: "12px 24px",
              backgroundColor: "#f8fafc",
              borderBottom: "1px solid #e2e8f0",
              display: "flex",
              flexWrap: "wrap",
              alignItems: "center",
              gap: 8,
            }}
          >
            <span
              style={{
                fontSize: 11,
                fontWeight: 700,
                color: "#64748b",
                textTransform: "uppercase",
                letterSpacing: "0.05em",
                marginRight: 4,
              }}
            >
              ⚡ Actions:
            </span>

            {/* Edit button */}
            {onEdit && (
              <button
                onClick={() => onEdit(row)}
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#ecfdf5",
                  color: "#059669",
                  border: "1px solid #a7f3d0",
                }}
              >
                ✏️ Edit
              </button>
            )}

            {/* Generate Draft button — when status = IN_REVIEW or CHANGES_REQUESTED */}
            {showGenerate && (
              <button
                onClick={() => onGenerate!(row)}
                disabled={generating}
                style={{
                  ...actionBtnStyle,
                  backgroundColor: generating ? "#9ca3af" : "#7c3aed",
                  color: "#fff",
                  cursor: generating ? "not-allowed" : "pointer",
                }}
              >
                {generating ? "⏳ Generating..." : "📄 Generate Draft"}
              </button>
            )}

            {/* Confirm button — when status = DRAFT_READY */}
            {showConfirm && (
              <button
                onClick={() => onConfirm!(row)}
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#10b981",
                  color: "#fff",
                }}
              >
                ✅ Confirm Draft
              </button>
            )}

            {/* Request Changes button — when status = DRAFT_READY */}
            {showRequestChanges && (
              <button
                onClick={() => onRequestChanges!(row)}
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#fef2f2",
                  color: "#dc2626",
                  border: "1px solid #fca5a5",
                }}
              >
                ↩ Request Changes
              </button>
            )}

            {/* Download PDF — if draft exists */}
            {hasDraft && (
              <button
                onClick={() =>
                  downloadDraftFile(row.id, "pdf", row.inquiry_ref)
                }
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#10b981",
                  color: "#fff",
                }}
              >
                📥 Download PDF
              </button>
            )}

            {/* Download Word — if draft exists */}
            {hasDraft && (
              <button
                onClick={() =>
                  downloadDraftFile(row.id, "docx", row.inquiry_ref)
                }
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#3b82f6",
                  color: "#fff",
                }}
              >
                📥 Download Word
              </button>
            )}

            {/* Delete — pushed to the right */}
            {onDelete && (
              <button
                onClick={() => onDelete(row)}
                style={{
                  ...actionBtnStyle,
                  backgroundColor: "#fef2f2",
                  color: "#dc2626",
                  border: "1px solid #fca5a5",
                  marginLeft: "auto",
                }}
              >
                🗑 Delete
              </button>
            )}
          </div>
        )}

        {/* ── Body ────────────────────────────────────────────────── */}
        <div className={styles.formBody}>
          {/* Inquiry Information */}
          <SectionHeader title="Inquiry Information" />
          <div className={styles.grid2}>
            <Field label="Reference No." value={row.inquiry_ref} mono />
            <Field label="Inquiry Type" value={typeCfg.label} />

            {/* ✅ NEW — Certification Body */}
            <BadgeField label="Certification Body">
              {certBody ? (
                <span
                  style={{
                    padding: "3px 12px",
                    borderRadius: 8,
                    fontSize: 12,
                    fontWeight: 700,
                    background:
                      certBody === "QRS"
                        ? "linear-gradient(135deg, #ede9fe 0%, #ddd6fe 100%)"
                        : "linear-gradient(135deg, #cffafe 0%, #a5f3fc 100%)",
                    color: certBody === "QRS" ? "#6d28d9" : "#0e7490",
                    border: `1px solid ${
                      certBody === "QRS" ? "#c4b5fd" : "#67e8f9"
                    }`,
                  }}
                >
                  {certBody === "QRS" ? "🏢 QRS" : "🏛 TQS"}
                </span>
              ) : (
                <span style={{ color: "#9ca3af" }}>—</span>
              )}
            </BadgeField>

            {/* ✅ NEW — Audit Stage */}
            <BadgeField label="Audit Stage">
              {auditStage ? (
                <span
                  style={{
                    padding: "3px 12px",
                    borderRadius: 8,
                    fontSize: 12,
                    fontWeight: 600,
                    backgroundColor: "#f5f3ff",
                    color: "#6d28d9",
                    border: "1px solid #ddd6fe",
                  }}
                >
                  🎯 {auditStage}
                </span>
              ) : (
                <span style={{ color: "#9ca3af" }}>—</span>
              )}
            </BadgeField>

            <Field
              label="Audit Date"
              value={formatDisplayDate(row.audit_date)}
            />
            <Field label="Auditor Name" value={row.auditor_name} />
            <Field
              label="Previous Cert. No."
              value={row.previous_cert_no}
              mono
            />
            <Field label="Status" value={statusCfg.label} />
          </div>

          {(row.certificate_number ||
            row.issue_date ||
            row.expiry_date ||
            row.accreditation_body ||
            (row as any).surveillance_audit_due ||
            (row as any).recertification_due) && (
            <>
              <SectionHeader title="📄 Certificate Details" />
              <div className={styles.grid2}>
                <Field
                  label="Certificate No."
                  value={row.certificate_number}
                  mono
                  fullWidth
                />
                <Field
                  label="Issue Date"
                  value={formatDisplayDate(row.issue_date)}
                />
                <Field
                  label="Expiry Date"
                  value={formatDisplayDate(row.expiry_date)}
                />
                <Field label="EA Code" value={row.accreditation_body} />
                {/* ✅ NEW */}
                <Field
                  label="Surv. Audit On or Before"
                  value={formatDisplayDate((row as any).surveillance_audit_due)}
                />
                <Field
                  label="Re-certification Due On"
                  value={formatDisplayDate((row as any).recertification_due)}
                />
              </div>
            </>
          )}

          {/* Scope of Work */}
          {row.scope_of_work && row.scope_of_work !== "—" && (
            <>
              <SectionHeader title="Scope of Work" />
              <div className={`${styles.formGroup} ${styles.full}`}>
                <div
                  style={{
                    padding: "10px 14px",
                    borderRadius: 8,
                    border: "1px solid #e5e7eb",
                    backgroundColor: "#f9fafb",
                    fontSize: 13,
                    color: "#374151",
                    whiteSpace: "pre-line",
                    lineHeight: 1.6,
                  }}
                >
                  {row.scope_of_work}
                </div>
              </div>
            </>
          )}

          {/* ISO Standards */}
          {row.standards?.length > 0 && (
            <>
              <SectionHeader title="ISO Standards" />
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {row.standards.map((s) => (
                  <span
                    key={s.id}
                    style={{
                      padding: "4px 12px",
                      borderRadius: 8,
                      fontSize: 12,
                      fontWeight: 600,
                      backgroundColor: "#dbeafe",
                      color: "#1e40af",
                    }}
                  >
                    {s.name}
                  </span>
                ))}
              </div>
            </>
          )}

          {/* ✅ NEW — Trade License / Previous Certificate Copies */}
          {documents.length > 0 && (
            <>
              <SectionHeader
                title={`📎 Trade License / Previous Certificate Copies (${documents.length})`}
              />
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {documents.map((doc, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "10px 14px",
                      backgroundColor: "#f0fdfa",
                      border: "1px solid #99f6e4",
                      borderRadius: 8,
                      fontSize: 13,
                    }}
                  >
                    <span
                      style={{
                        fontSize: 11,
                        fontWeight: 700,
                        padding: "3px 10px",
                        borderRadius: 6,
                        backgroundColor: "#0f766e",
                        color: "#fff",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {docTypeLabel(doc.type)}
                    </span>
                    <span
                      style={{
                        flex: 1,
                        color: "#0f766e",
                        fontWeight: 600,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                      title={doc.filename}
                    >
                      {doc.filename}
                    </span>
                    <span style={{ fontSize: 11, color: "#6b7280" }}>
                      {formatDisplayDate(doc.uploaded_at)}
                    </span>
                    <button
                      onClick={() => openDocument(doc.path)}
                      style={{
                        padding: "5px 14px",
                        borderRadius: 6,
                        border: "1px solid #99f6e4",
                        backgroundColor: "#fff",
                        color: "#0f766e",
                        cursor: "pointer",
                        fontSize: 12,
                        fontWeight: 600,
                      }}
                    >
                      📥 Open
                    </button>
                  </div>
                ))}
              </div>
            </>
          )}

          {/* Team */}
          <SectionHeader title="Team" />
          <div className={styles.grid2}>
            <Field label="Submitted By" value={submittedBy} />
            <Field label="Assigned To" value={assignedTo} />
          </div>

          {/* Notes */}
          {row.notes && (
            <>
              <SectionHeader title="Notes" />
              <div className={`${styles.formGroup} ${styles.full}`}>
                <div
                  style={{
                    padding: "10px 14px",
                    borderRadius: 8,
                    border: "1px solid #e5e7eb",
                    backgroundColor: "#f9fafb",
                    fontSize: 13,
                    color: "#374151",
                    whiteSpace: "pre-line",
                    lineHeight: 1.6,
                  }}
                >
                  {row.notes}
                </div>
              </div>
            </>
          )}

          {/* Change Request Notes */}
          {row.change_request_notes && (
            <>
              <SectionHeader title="⚠️ Change Request Notes" />
              <div className={`${styles.formGroup} ${styles.full}`}>
                <div
                  style={{
                    padding: "10px 14px",
                    borderRadius: 8,
                    border: "1px solid #fecaca",
                    backgroundColor: "#fef2f2",
                    fontSize: 13,
                    color: "#991b1b",
                    whiteSpace: "pre-line",
                    lineHeight: 1.6,
                  }}
                >
                  {row.change_request_notes}
                </div>
              </div>
            </>
          )}
        </div>

        {/* ── Footer ──────────────────────────────────────────────── */}
        <div className={styles.modalFooter}>
          <button type="button" onClick={onClose} className={styles.cancelBtn}>
            Close
          </button>
        </div>
      </div>
    </div>
  );
}