"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import ui from "../../audit-requests/Form/BatchForm.module.css";
import { fetchApi } from "@/lib/api/http";
import {
  createTrainingCertificate,
  batchCreateTrainingCertificates,
  updateTrainingCertificate,
  getTrainingCertificate,
  TRAINING_API_BASE_URL,
} from "@/lib/api/training-certificate.api";
import type {
  CreatedTrainingCertificate,
  VerificationDomain,
} from "@/lib/api/types/training-certificate.types";
import TrainingSuccessModal from "./TrainingSuccessModal";

// ─── Options ────────────────────────────────────────────────────────────────
type StdOption = { value: number; label: string };

const DOMAIN_VALUES: VerificationDomain[] = ["local", "international"];
const domainLabel = (d: VerificationDomain) =>
  d === "local" ? "Local" : "International";

const selectPortal = {
  menuPortalTarget:
    typeof document !== "undefined" ? document.body : undefined,
  styles: { menuPortal: (base: any) => ({ ...base, zIndex: 3000 }) },
};

type ParticipantCard = {
  _key: string;
  participant_name: string;
  participant_company: string;
  certificate_no: string; // optional manual — empty = auto QRS-TRG-YY-NNN
};

const emptyParticipant = (): ParticipantCard => ({
  _key: Math.random().toString(36).slice(2),
  participant_name: "",
  participant_company: "",
  certificate_no: "",
});

interface Props {
  onClose: () => void;
  onSuccess: () => void;
  editId?: number | null;
}

export default function TrainingCertificateForm({
  onClose,
  onSuccess,
  editId,
}: Props) {
  const isEdit = !!editId;

  // ── Shared course details ────────────────────────────────────────────────
  const [courseTitle, setCourseTitle] = useState("");
  const [standardId, setStandardId] = useState<number | "">("");
  const [location, setLocation] = useState("Abu Dhabi, UAE");
  const [trainingDate, setTrainingDate] = useState("");
  const [trainingDateEnd, setTrainingDateEnd] = useState("");
  const [validUntil, setValidUntil] = useState("");
  const [domain, setDomain] = useState<VerificationDomain>("local");

  const [standards, setStandards] = useState<StdOption[]>([]);
  const [participants, setParticipants] = useState<ParticipantCard[]>([
    emptyParticipant(),
  ]);
  const [submitting, setSubmitting] = useState(false);

  // Success screen state
  const [successItems, setSuccessItems] = useState<
    CreatedTrainingCertificate[] | null
  >(null);
  const [successBatchRef, setSuccessBatchRef] = useState<string | null>(null);

  // ── Load standards for the optional dropdown ─────────────────────────────
  useEffect(() => {
    fetchApi<Array<{ id: number; name: string; title: string }>>(
      `${TRAINING_API_BASE_URL}/standards`,
    )
      .then((res) =>
        setStandards(
          (res || []).map((s) => ({ value: s.id, label: s.title || s.name })),
        ),
      )
      .catch(() => {
        /* optional — form works without the list */
      });
  }, []);

  // ── Edit mode: load existing certificate ─────────────────────────────────
  useEffect(() => {
    if (!isEdit || !editId) return;
    getTrainingCertificate(editId)
      .then(({ certificate: c }) => {
        setCourseTitle(c.course_title || "");
        setStandardId(c.standard?.id ?? "");
        setLocation(c.training_location || "");
        setTrainingDate(
          c.training_date ? String(c.training_date).slice(0, 10) : "",
        );
        setTrainingDateEnd(
          c.training_date_end ? String(c.training_date_end).slice(0, 10) : "",
        );
        setValidUntil(c.valid_until ? String(c.valid_until).slice(0, 10) : "");
        setDomain(c.verification_domain || "local");
        setParticipants([
          {
            _key: "edit",
            participant_name: c.participant_name || "",
            participant_company: c.participant_company || "",
            certificate_no: c.certificate_no || "",
          },
        ]);
      })
      .catch(() => toast.error("Failed to load training certificate"));
  }, [isEdit, editId]);

  // ── Participant card helpers ─────────────────────────────────────────────
  const setParticipant = (key: string, patch: Partial<ParticipantCard>) =>
    setParticipants((prev) =>
      prev.map((p) => (p._key === key ? { ...p, ...patch } : p)),
    );

  const addParticipant = () =>
    setParticipants((prev) => [...prev, emptyParticipant()]);

  const removeParticipant = (key: string) =>
    setParticipants((prev) =>
      prev.length > 1 ? prev.filter((p) => p._key !== key) : prev,
    );

  // Duplicate a participant card — keeps the company (same employer, next
  // person), clears the name and certificate number.
  const duplicateParticipant = (key: string) =>
    setParticipants((prev) => {
      const idx = prev.findIndex((p) => p._key === key);
      if (idx === -1) return prev;
      const src = prev[idx];
      const copy: ParticipantCard = {
        _key: Math.random().toString(36).slice(2),
        participant_name: "",
        participant_company: src.participant_company,
        certificate_no: "",
      };
      return [...prev.slice(0, idx + 1), copy, ...prev.slice(idx + 1)];
    });

  // ── Validation ───────────────────────────────────────────────────────────
  const validate = (): string | null => {
    if (!courseTitle.trim()) return "Course title is required.";
    if (!location.trim()) return "Training location is required.";
    if (!trainingDate) return "Training date is required.";
    for (let i = 0; i < participants.length; i++) {
      const p = participants[i];
      const n = i + 1;
      if (!p.participant_name.trim())
        return `Participant ${n}: name is required.`;
    }
    // duplicate manual certificate numbers within the form
    const manualNos = participants
      .map((p) => p.certificate_no.trim().toUpperCase())
      .filter(Boolean);
    const dup = manualNos.find((no, i) => manualNos.indexOf(no) !== i);
    if (dup) return `Certificate number ${dup} is entered twice.`;
    return null;
  };

  // ── Submit ───────────────────────────────────────────────────────────────
  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    const v = validate();
    if (v) return toast.error(v);

    const shared = {
      course_title: courseTitle.trim(),
      standard_id: standardId === "" ? undefined : Number(standardId),
      training_location: location.trim(),
      training_date: trainingDate,
      training_date_end: trainingDateEnd || undefined,
      valid_until: validUntil || undefined,
      verification_domain: domain,
    };

    setSubmitting(true);
    try {
      // ── EDIT ──
      if (isEdit && editId) {
        const p = participants[0];
        await updateTrainingCertificate(editId, {
          ...shared,
          participant_name: p.participant_name.trim(),
          participant_company: p.participant_company.trim() || undefined,
          certificate_no: p.certificate_no.trim() || undefined,
        });
        toast.success("Training certificate updated");
        onSuccess();
        onClose();
        return;
      }

      // ── CREATE ──
      const hasManualNumbers = participants.some((p) =>
        p.certificate_no.trim(),
      );

      if (participants.length > 1 && !hasManualNumbers) {
        // Whole session in one batch — grouped under a batch reference
        const res = await batchCreateTrainingCertificates({
          ...shared,
          participants: participants.map((p) => ({
            participant_name: p.participant_name.trim(),
            participant_company: p.participant_company.trim() || undefined,
          })),
        });
        toast.success(`${res.count} certificates created — QRs ready`);
        setSuccessItems(res.certificates);
        setSuccessBatchRef(res.batch_ref);
      } else {
        // One-by-one (single participant, or manual numbers involved)
        const created: CreatedTrainingCertificate[] = [];
        for (const p of participants) {
          const res = await createTrainingCertificate({
            ...shared,
            participant_name: p.participant_name.trim(),
            participant_company: p.participant_company.trim() || undefined,
            certificate_no: p.certificate_no.trim() || undefined,
          });
          created.push(res);
        }
        toast.success(
          `${created.length} certificate${created.length > 1 ? "s" : ""} created — QR${created.length > 1 ? "s" : ""} ready`,
        );
        setSuccessItems(created);
        setSuccessBatchRef(null);
      }
      onSuccess();
    } catch (err: any) {
      toast.error(err?.message || "Something went wrong creating the certificates.");
    } finally {
      setSubmitting(false);
    }
  };

  // ── Success screen (QRs + downloads) replaces the form after create ──────
  if (successItems) {
    return (
      <TrainingSuccessModal
        items={successItems}
        batchRef={successBatchRef}
        onClose={() => {
          setSuccessItems(null);
          setSuccessBatchRef(null);
          onClose();
        }}
      />
    );
  }

  return (
    <div className={ui.page}>
      {/* ══ Top bar ═══════════════════════════════════════════════════════ */}
      <div className={ui.topbar}>
        <div className={ui.topbarLeft}>
          <button
            type="button"
            className={ui.backBtn}
            onClick={onClose}
            disabled={submitting}
            aria-label="Back"
          >
            ←
          </button>
          <div>
            <h1 className={ui.pageTitle}>
              {isEdit
                ? "Edit Training Certificate"
                : "Issue Training Certificates"}
            </h1>
            <p className={ui.pageSub}>
              {isEdit
                ? `Editing ${participants[0]?.certificate_no || "certificate"}`
                : `One certificate is created per participant · ${participants.length} participant${participants.length > 1 ? "s" : ""} added`}
            </p>
          </div>
        </div>
        <div className={ui.topbarActions}>
          <button
            type="button"
            className={ui.btnGhost}
            onClick={onClose}
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="button"
            className={ui.btnPrimary}
            onClick={() => handleSubmit()}
            disabled={submitting}
          >
            {submitting
              ? isEdit
                ? "Saving…"
                : "Issuing certificates…"
              : isEdit
                ? "Save Changes"
                : `Issue ${participants.length} Certificate${participants.length > 1 ? "s" : ""}`}
          </button>
        </div>
      </div>

      {/* ══ Content ═══════════════════════════════════════════════════════ */}
      <div className={ui.content}>
        <form onSubmit={handleSubmit}>
          {/* ── Step 1 · Course details (shared) ──────────────────────────── */}
          <div className={ui.card}>
            <div className={ui.cardHead}>
              <div className={ui.cardHeadLeft}>
                <span className={ui.stepBadge}>1</span>
                <div>
                  <p className={ui.cardTitle}>Course Details</p>
                  <p className={ui.cardHint}>
                    These settings apply to every participant in this session
                  </p>
                </div>
              </div>
            </div>
            <div className={ui.cardBody}>
              <div className={ui.grid}>
                <div className={ui.full}>
                  <label className={`${ui.label} ${ui.req}`}>
                    Course Title
                  </label>
                  <input
                    type="text"
                    className={ui.input}
                    value={courseTitle}
                    onChange={(e) => setCourseTitle(e.target.value)}
                    placeholder="e.g., ISO 45001:2018 Awareness & Internal Audit Training"
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.label}>Related Standard</label>
                  <Select
                    classNamePrefix="rselect"
                    options={standards}
                    isClearable
                    value={standards.find((o) => o.value === standardId) ?? null}
                    onChange={(opt) =>
                      setStandardId(opt ? (opt as StdOption).value : "")
                    }
                    placeholder="Optional — pick a standard…"
                    {...selectPortal}
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Verification Domain</label>
                  <div className={ui.groupToggle}>
                    {DOMAIN_VALUES.map((d) => (
                      <button
                        key={d}
                        type="button"
                        className={`${ui.groupBtn} ${domain === d ? ui.groupBtnActive : ""}`}
                        onClick={() => setDomain(d)}
                      >
                        {domainLabel(d)}
                        {domain === d && <span className={ui.groupCheck}>✓</span>}
                      </button>
                    ))}
                  </div>
                  <div className={ui.helper}>
                    QR codes open the verification page on{" "}
                    {domain === "local" ? "qrsyst.com" : "the international domain"}
                  </div>
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Training Location</label>
                  <input
                    type="text"
                    className={ui.input}
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                    placeholder="e.g., Abu Dhabi, UAE"
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Training Date</label>
                  <input
                    type="date"
                    className={ui.input}
                    value={trainingDate}
                    onChange={(e) => setTrainingDate(e.target.value)}
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.label}>Training Date End</label>
                  <input
                    type="date"
                    className={ui.input}
                    value={trainingDateEnd}
                    onChange={(e) => setTrainingDateEnd(e.target.value)}
                  />
                  <div className={ui.helper}>
                    Optional — for multi-day trainings (e.g. 6 and 7 July 2026)
                  </div>
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.label}>Valid Until</label>
                  <input
                    type="date"
                    className={ui.input}
                    value={validUntil}
                    onChange={(e) => setValidUntil(e.target.value)}
                  />
                  <div className={ui.helper}>
                    Leave empty — certificate never expires
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ── Participant cards ─────────────────────────────────────────── */}
          {participants.map((p, i) => (
            <div key={p._key} className={ui.card}>
              <div className={ui.cardHead}>
                <div className={ui.cardHeadLeft}>
                  <span className={`${ui.stepBadge} ${ui.clientBadge}`}>
                    {i + 1}
                  </span>
                  <div>
                    <p className={ui.cardTitle}>
                      {p.participant_name || `Participant ${i + 1}`}
                    </p>
                    <p className={ui.cardHint}>
                      {p.certificate_no.trim()
                        ? `Manual number: ${p.certificate_no.trim().toUpperCase()}`
                        : "Certificate number auto-generates (QRS-TRG-YY-NNN)"}
                      {p.participant_company && ` · ${p.participant_company}`}
                    </p>
                  </div>
                </div>
                {!isEdit && (
                  <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
                    <button
                      type="button"
                      className={ui.duplicateBtn}
                      onClick={() => duplicateParticipant(p._key)}
                      disabled={submitting}
                      title="Copy this card for another participant from the same company"
                    >
                      ⧉ Duplicate
                    </button>
                    {participants.length > 1 && (
                      <button
                        type="button"
                        className={ui.removeClientBtn}
                        onClick={() => removeParticipant(p._key)}
                        disabled={submitting}
                      >
                        Remove
                      </button>
                    )}
                  </div>
                )}
              </div>

              <div className={ui.cardBody}>
                <div className={ui.grid}>
                  <div className={`${ui.field} ${ui.half}`}>
                    <label className={ui.req}>Participant Name</label>
                    <input
                      type="text"
                      className={ui.input}
                      value={p.participant_name}
                      onChange={(e) =>
                        setParticipant(p._key, {
                          participant_name: e.target.value,
                        })
                      }
                      placeholder="e.g., Wael Meseef Al Betar"
                    />
                  </div>

                  <div className={`${ui.field} ${ui.half}`}>
                    <label className={ui.label}>Company</label>
                    <input
                      type="text"
                      className={ui.input}
                      value={p.participant_company}
                      onChange={(e) =>
                        setParticipant(p._key, {
                          participant_company: e.target.value,
                        })
                      }
                      placeholder="e.g., Galva Coat for Galvanizing & Lighting Poles"
                    />
                  </div>

                  <div className={ui.full}>
                    <label className={ui.label}>Certificate No.</label>
                    <input
                      type="text"
                      className={ui.input}
                      value={p.certificate_no}
                      onChange={(e) =>
                        setParticipant(p._key, {
                          certificate_no: e.target.value,
                        })
                      }
                      placeholder="Leave empty — auto-generated as QRS-TRG-YY-NNN"
                    />
                    <div className={ui.helper}>
                      Only fill this for old/legacy certificates with an
                      existing number
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}

          {!isEdit && (
            <button
              type="button"
              className={ui.addClientBtn}
              onClick={addParticipant}
              disabled={submitting}
            >
              + Add Another Participant
            </button>
          )}

          <div className={ui.note}>
            <span>💡</span>
            <span>
              {isEdit ? (
                <>
                  Changes save directly to this certificate — the QR code and
                  verification link stay the same.
                </>
              ) : (
                <>
                  This creates <strong>{participants.length}</strong> training
                  certificate{participants.length > 1 ? "s" : ""} — one per
                  participant, each with its own QR code. Download the QRs on
                  the next screen, place them on the printed certificates,
                  sign, then upload the scans from the table&apos;s{" "}
                  <strong>View</strong> action to activate them.
                </>
              )}
            </span>
          </div>
        </form>
      </div>
    </div>
  );
}