"use client";

import React from "react";
import styles from "../../commonstyle/FormStyles.module.css";
import {
  ScheduleStatusBadge,
  RowStatusBadge,
  AuditTypeBadge,
  AuditModeBadge,
} from "../components/AuditBadges";
import {
  formatDate,
  formatDateTime,
} from "@/lib/api/mappers/audit-schedule.mappers";
import type { AuditScheduleRow } from "@/lib/api/types/audit-schedule.types";

interface Props {
  row: AuditScheduleRow | null;
  onClose: () => void;
}

export default function AuditScheduleViewModal({ row, onClose }: Props) {
  if (!row) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 900, maxHeight: "90vh", overflow: "auto" }}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>📅 {row.title}</h2>
            <p
              style={{
                fontSize: 13,
                color: "#6b7280",
                margin: "4px 0 0",
              }}
            >
              {formatDate(row.schedule_date)} · {row.client_group}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose}>
            ✕
          </button>
        </div>

        <div className={styles.modalBody}>
          {/* Summary panel */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
              gap: 12,
              marginBottom: 24,
            }}
          >
            <Info label="Status">
              <ScheduleStatusBadge status={row.status} />
            </Info>
            <Info label="Coordinator">
              <div style={{ fontWeight: 600 }}>{row.coordinator_name}</div>
              <div style={{ fontSize: 11, color: "#9ca3af" }}>
                {row.coordinator_email}
              </div>
            </Info>
            <Info label="Source Email">
              <span style={{ fontSize: 12 }}>{row.source_email}</span>
            </Info>
            <Info label="Created">
              <span style={{ fontSize: 12 }}>
                {formatDateTime(row.created_at)}
              </span>
            </Info>
          </div>

          {/* Audit rows */}
          <h3
            style={{
              fontSize: 14,
              fontWeight: 700,
              color: "#0f172a",
              marginBottom: 8,
              paddingBottom: 6,
              borderBottom: "2px solid #e5e7eb",
            }}
          >
            Audit Rows ({row.rows.length})
          </h3>

          {row.rows.length === 0 ? (
            <div
              style={{
                padding: 24,
                textAlign: "center",
                color: "#9ca3af",
                background: "#f9fafb",
                borderRadius: 8,
              }}
            >
              No audit rows in this schedule.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {row.rows.map((r) => (
                <div
                  key={r.id}
                  style={{
                    padding: 14,
                    background: r.status === "CANCELLED" ? "#fef2f2" : "#f8fafc",
                    border: `1px solid ${
                      r.status === "CANCELLED" ? "#fecaca" : "#e2e8f0"
                    }`,
                    borderRadius: 8,
                  }}
                >
                  {/* Header row */}
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "flex-start",
                      marginBottom: 8,
                    }}
                  >
                    <div>
                      <div
                        style={{
                          fontFamily: "monospace",
                          fontWeight: 700,
                          fontSize: 14,
                          color: "#0f172a",
                        }}
                      >
                        {r.audit_code}
                      </div>
                      <div
                        style={{
                          fontSize: 13,
                          fontWeight: 600,
                          marginTop: 2,
                        }}
                      >
                        {r.company?.name ?? "—"}
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                      <AuditTypeBadge type={r.audit_type} />
                      <AuditModeBadge mode={r.audit_mode} />
                      <RowStatusBadge status={r.status} />
                    </div>
                  </div>

                  {/* Details grid */}
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
                      gap: 8,
                      fontSize: 12,
                      color: "#475569",
                    }}
                  >
                    {r.audit_stage && (
                      <div>
                        <strong>Stage:</strong> {r.audit_stage}
                      </div>
                    )}
                    {r.accreditation && (
                      <div>
                        <strong>Accreditation:</strong> {r.accreditation}
                      </div>
                    )}
                    <div>
                      <strong>Auditor:</strong>{" "}
                      {r.lead_auditor
                        ? `${r.lead_auditor.firstName} ${r.lead_auditor.lastName}`
                        : "—"}
                    </div>
                    <div>
                      <strong>Time:</strong>{" "}
                      {r.audit_time_label ?? r.audit_time ?? "—"}
                    </div>
                    {r.standards && r.standards.length > 0 && (
                      <div style={{ gridColumn: "1/-1" }}>
                        <strong>Standards:</strong>{" "}
                        {r.standards.map((s) => s.name).join(", ")}
                      </div>
                    )}
                  </div>

                  {/* Cancellation info */}
                  {r.status === "CANCELLED" && r.cancellation_reason && (
                    <div
                      style={{
                        marginTop: 10,
                        padding: 10,
                        background: "#fef2f2",
                        border: "1px solid #fecaca",
                        borderRadius: 6,
                        fontSize: 12,
                        color: "#7f1d1d",
                      }}
                    >
                      <strong>❌ Cancelled:</strong> {r.cancellation_reason}
                      {r.cancellation_notes && <> — {r.cancellation_notes}</>}
                      <div style={{ marginTop: 4, fontSize: 11, color: "#9ca3af" }}>
                        {r.cancelled_at && `On ${formatDateTime(r.cancelled_at)}`}
                        {r.cancelled_by &&
                          ` by ${r.cancelled_by.firstName} ${r.cancelled_by.lastName}`}
                      </div>
                    </div>
                  )}

                  {/* Reschedule info */}
                  {r.reschedule_count > 0 && (
                    <div
                      style={{
                        marginTop: 8,
                        padding: 10,
                        background: "#cffafe",
                        border: "1px solid #67e8f9",
                        borderRadius: 6,
                        fontSize: 12,
                        color: "#0e7490",
                      }}
                    >
                      <strong>🔄 Rescheduled {r.reschedule_count}×</strong>
                      {r.original_audit_date && (
                        <> · originally {formatDate(r.original_audit_date)}</>
                      )}
                      {r.reschedule_reason && (
                        <div style={{ marginTop: 4 }}>{r.reschedule_reason}</div>
                      )}
                    </div>
                  )}

                  {r.notes && (
                    <div
                      style={{
                        marginTop: 8,
                        fontSize: 12,
                        color: "#6b7280",
                        fontStyle: "italic",
                      }}
                    >
                      📝 {r.notes}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}

          {/* Schedule notes */}
          {row.notes && row.notes !== "—" && (
            <div style={{ marginTop: 24 }}>
              <h3
                style={{
                  fontSize: 14,
                  fontWeight: 700,
                  color: "#0f172a",
                  marginBottom: 8,
                  paddingBottom: 6,
                  borderBottom: "2px solid #e5e7eb",
                }}
              >
                Schedule Notes
              </h3>
              <div
                style={{
                  padding: 12,
                  background: "#fffbeb",
                  border: "1px solid #fef3c7",
                  borderRadius: 8,
                  color: "#854d0e",
                  fontSize: 13,
                  lineHeight: 1.6,
                }}
              >
                {row.notes}
              </div>
            </div>
          )}
        </div>

        <div className={styles.modalFooter}>
          <button className={styles.btnSecondary} onClick={onClose}>
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

function Info({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ padding: 10, background: "#f8fafc", borderRadius: 6 }}>
      <div
        style={{
          fontSize: 10,
          fontWeight: 700,
          color: "#9ca3af",
          textTransform: "uppercase",
          marginBottom: 4,
        }}
      >
        {label}
      </div>
      <div>{children}</div>
    </div>
  );
}
