"use client";

import React, { useRef, useState } from "react";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import {
  uploadTrainingScan,
  updateTrainingCertificate,
} from "@/lib/api/training-certificate.api";
import type {
  TrainingRowType,
  TrainingStatus,
} from "@/lib/api/types/training-certificate.types";
import { StatusBadge } from "../TrainingRow";

interface Props {
  row: TrainingRowType | null;
  onClose: () => void;
  onUpdated?: () => void;
  canEdit?: boolean;
}

function Item({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div
        style={{
          fontSize: 10.5,
          fontWeight: 700,
          color: "#94a3b8",
          textTransform: "uppercase",
          letterSpacing: 0.5,
          marginBottom: 3,
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontSize: 13.5,
          fontWeight: 600,
          color: "#0f172a",
          wordBreak: "break-word",
        }}
      >
        {value || "—"}
      </div>
    </div>
  );
}

export default function TrainingViewModal({
  row,
  onClose,
  onUpdated,
  canEdit = false,
}: Props) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [changing, setChanging] = useState(false);

  if (!row) return null;

  const fmt = (d?: string | null) =>
    d
      ? new Date(d).toLocaleDateString("en-GB", {
          day: "numeric",
          month: "long",
          year: "numeric",
        })
      : "—";

  const handleUpload = async (file: File) => {
    setUploading(true);
    try {
      const res = await uploadTrainingScan(row.id, file);
      toast.success(res.message || "Scan uploaded — certificate active");
      onUpdated?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message ?? "Upload failed");
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  };

  const setStatus = async (status: TrainingStatus) => {
    if (
      (status === "revoked" || status === "fake") &&
      !window.confirm(
        `Mark certificate ${row.certificate_no} as ${status.toUpperCase()}?`,
      )
    ) {
      return;
    }
    setChanging(true);
    try {
      await updateTrainingCertificate(row.id, { status });
      toast.success(`Status changed to ${status}`);
      onUpdated?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message ?? "Status change failed");
    } finally {
      setChanging(false);
    }
  };

  const statusBtn = (border: string, color: string): React.CSSProperties => ({
    padding: "7px 14px",
    borderRadius: 999,
    fontSize: 12,
    fontWeight: 700,
    cursor: changing ? "wait" : "pointer",
    background: "#fff",
    border: `1px solid ${border}`,
    color,
    opacity: changing ? 0.6 : 1,
  });

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        style={{ maxWidth: 720, width: "95%" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>🎓 Training Certificate</h2>
            <p
              style={{
                margin: "4px 0 0",
                fontSize: 12,
                color: "#64748b",
                fontFamily: "'IBM Plex Mono', monospace",
                fontWeight: 700,
              }}
            >
              {row.certificate_no}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">
            ×
          </button>
        </div>

        <div className={styles.formBody}>
          {/* Status row */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              marginBottom: 18,
            }}
          >
            <StatusBadge status={row.status} />
            {row.batch_ref && (
              <span
                style={{
                  fontSize: 11,
                  color: "#94a3b8",
                  fontFamily: "'IBM Plex Mono', monospace",
                }}
              >
                Batch: {row.batch_ref}
              </span>
            )}
          </div>

          {/* Details grid */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: "14px 24px",
              padding: 16,
              border: "1px solid #e2e8f0",
              borderRadius: 10,
              background: "#f8fafc",
              marginBottom: 16,
            }}
          >
            <Item label="Participant" value={row.participant_name} />
            <Item label="Company" value={row.participant_company} />
            <Item label="Course" value={row.course_title} />
            <Item label="Related Standard" value={row.standard_name} />
            <Item label="Training Location" value={row.training_location} />
            <Item label="Training Date" value={fmt(row.training_date)} />
            <Item
              label="Valid Until"
              value={row.valid_until ? fmt(row.valid_until) : "No expiry"}
            />
            <Item
              label="Verification Domain"
              value={row.verification_domain}
            />
          </div>

          {/* Signed scan section */}
          <div
            style={{
              padding: 16,
              border: "1px solid #e2e8f0",
              borderRadius: 10,
              marginBottom: 16,
            }}
          >
            <div
              style={{
                fontSize: 11,
                fontWeight: 800,
                color: "#94a3b8",
                letterSpacing: ".08em",
                textTransform: "uppercase",
                marginBottom: 8,
              }}
            >
              Signed Physical Copy
            </div>

            {row.scan_pdf_url ? (
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 10,
                  flexWrap: "wrap",
                }}
              >
                <a
                  href={row.scan_pdf_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    fontSize: 13,
                    fontWeight: 700,
                    color: "#0f766e",
                    textDecoration: "none",
                  }}
                >
                  📄 View uploaded scan
                </a>
                <span style={{ fontSize: 11, color: "#94a3b8" }}>
                  Uploaded: {fmt(row.scan_uploaded_at)}
                </span>
              </div>
            ) : (
              <p style={{ fontSize: 12.5, color: "#b45309", margin: 0 }}>
                ⏳ No scan uploaded yet — the certificate stays{" "}
                <strong>pending_scan</strong> until the signed copy is uploaded.
              </p>
            )}

            {canEdit && (
              <>
                <input
                  ref={fileRef}
                  type="file"
                  accept=".jpg,.jpeg,.png,.pdf"
                  style={{ display: "none" }}
                  onChange={(e) => {
                    const f = e.target.files?.[0];
                    if (f) handleUpload(f);
                  }}
                />
                <button
                  type="button"
                  onClick={() => fileRef.current?.click()}
                  disabled={uploading}
                  style={{
                    marginTop: 12,
                    padding: "8px 16px",
                    borderRadius: 999,
                    border: "none",
                    background:
                      "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
                    color: "#fff",
                    fontSize: 12.5,
                    fontWeight: 700,
                    cursor: uploading ? "wait" : "pointer",
                    opacity: uploading ? 0.6 : 1,
                  }}
                >
                  {uploading
                    ? "Uploading…"
                    : row.scan_pdf_url
                      ? "📤 Replace Scan (JPG/PNG/PDF)"
                      : "📤 Upload Scan (JPG/PNG/PDF)"}
                </button>
              </>
            )}
          </div>

          {/* Status actions */}
          {canEdit && (
            <div
              style={{
                padding: 16,
                border: "1px solid #e2e8f0",
                borderRadius: 10,
              }}
            >
              <div
                style={{
                  fontSize: 11,
                  fontWeight: 800,
                  color: "#94a3b8",
                  letterSpacing: ".08em",
                  textTransform: "uppercase",
                  marginBottom: 10,
                }}
              >
                Status Actions
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <button
                  type="button"
                  style={statusBtn("#bbf7d0", "#15803d")}
                  onClick={() => setStatus("active")}
                  disabled={changing}
                >
                  ✅ Set Active
                </button>
                <button
                  type="button"
                  style={statusBtn("#fecaca", "#b91c1c")}
                  onClick={() => setStatus("revoked")}
                  disabled={changing}
                >
                  🚫 Revoke
                </button>
                <button
                  type="button"
                  style={statusBtn("#fca5a5", "#7f1d1d")}
                  onClick={() => setStatus("fake")}
                  disabled={changing}
                >
                  ⚠️ Mark as Fake
                </button>
              </div>
            </div>
          )}
        </div>

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