"use client";

import { useState } from "react";
import Link from "next/link";
import { useLang } from "@/context/LanguageContext";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { Alert, Button, Input } from "@/components/ui";
import { api } from "@/lib/client";
import { IncrelogLogo } from "@/components/IncrelogLogo";
import { IconArrowRight, IconCheck, IconSearch } from "@/components/icons";
import type { PublicAccount } from "@/components/PaymentAccountCards";
import {
  AdmissionFormWizard,
  AdmissionStepper,
  WizardReviewRow,
  type AdmissionFormValues,
} from "@/components/AdmissionFormWizard";

/* Public admission application — students/guardians apply to their chosen
   institution without an account. Step wizard: Institution → the shared
   admission form (Student → Guardian & Contact → Address & Note → Review).
   The application lands in the institution's Admissions queue. */

interface PublicInstitution {
  name: string;
  code: string;
  type: string;
  address: string;
  district: string | null;
  subDistrict: string | null;
  eiin: string | null;
  classes: { id: number; name: string; nameBn: string }[];
  sessions: { id: number; name: string; nameBn: string }[] | null;
  admissionFee: { enabled: boolean; amount: number } | null;
  paymentAccounts: PublicAccount[] | null;
}

interface InstitutionSummary {
  name: string;
  code: string;
  type: string;
  district: string | null;
  subDistrict: string | null;
}

const emptyForm: AdmissionFormValues & { company: string } = {
  studentName: "", studentNameBn: "", classItemId: "", sessionItemId: "", gender: "MALE", dob: "",
  bloodGroup: "", religion: "",
  guardianName: "", guardianNameBn: "", guardianPhone: "",
  motherName: "", motherNameBn: "", studentPhone: "", email: "",
  address: "", permanentAddress: "", note: "",
  company: "", // honeypot — hidden from humans
};

const LAST_STEP = 4; // 0 institution · 1 student · 2 guardian · 3 address · 4 review

export default function ApplyPage() {
  const { t } = useLang();
  const a = t.applyPage;

  const stepLabels = [a.stepInstitution, a.stepStudent, a.stepGuardian, a.stepAddress, a.stepReview];

  // step 0 — find institution
  const [code, setCode] = useState("");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<InstitutionSummary[] | null>(null);
  const [searching, setSearching] = useState(false);
  const [finding, setFinding] = useState(false);

  // the application
  const [institution, setInstitution] = useState<PublicInstitution | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [step, setStep] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  // optional minimal tracking account (password alongside the email already given)
  const [wantAccount, setWantAccount] = useState(true);
  const [accountPassword, setAccountPassword] = useState("");

  // done screen (fee guidance lives on the /track page, not here)
  const [done, setDone] = useState<{
    reference: string;
    name: string;
    emailSent?: boolean;
    code?: string;
  } | null>(null);

  async function searchByName() {
    if (query.trim().length < 2) return;
    setSearching(true);
    setError("");
    try {
      const res = await api<{ institutions: InstitutionSummary[] }>(
        `/api/public/admissions/institutions?q=${encodeURIComponent(query.trim())}`
      );
      setResults(res.institutions);
    } catch {
      setError(t.common.tryAgain);
    } finally {
      setSearching(false);
    }
  }

  async function findByCode(raw?: string) {
    const value = (raw ?? code).trim();
    if (!value) return;
    setFinding(true);
    setError("");
    try {
      const res = await api<{ institution: PublicInstitution | null }>(
        `/api/public/admissions/institutions?code=${encodeURIComponent(value)}`
      );
      if (!res.institution) {
        setError(a.notFound);
        setInstitution(null);
      } else {
        setInstitution(res.institution);
        setResults(null);
        setStep(1); // found → move on to the student step
      }
    } catch {
      setError(a.notFound);
    } finally {
      setFinding(false);
    }
  }

  function goToStep(i: number) {
    setError("");
    setStep(i);
  }

  async function submit() {
    if (!institution || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const res = await api<{
        success: boolean;
        reference: string;
        institutionName: string;
        emailSent?: boolean;
      }>("/api/public/admissions/apply", {
        method: "POST",
        body: JSON.stringify({
          ...form,
          code: institution.code,
          classItemId: form.classItemId ? Number(form.classItemId) : null,
          sessionItemId: form.sessionItemId ? Number(form.sessionItemId) : null,
          dob: form.dob || null,
          password: wantAccount && accountPassword.trim().length >= 6 ? accountPassword.trim() : undefined,
        }),
      });
      setDone({
        reference: res.reference,
        name: res.institutionName,
        emailSent: res.emailSent,
        code: institution.code,
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : "";
      setError(
        msg === "RATE_LIMITED" ? a.rateLimited
          : msg === "INSTITUTION_NOT_FOUND" ? a.notFound
          : t.common.tryAgain
      );
    } finally {
      setSubmitting(false);
    }
  }

  function resetAll() {
    setInstitution(null);
    setForm(emptyForm);
    setCode("");
    setQuery("");
    setResults(null);
    setStep(0);
    setDone(null);
    setError("");
    setWantAccount(true);
    setAccountPassword("");
  }

  /* ---------------- success screen ---------------- */
  if (done) {
    return (
      <div className="ems-auth-wrapper ems-apply-page">
        <div className="container-fluid py-3">
          <div className="d-flex justify-content-between align-items-center py-2">
            <Link href="/" className="d-flex align-items-center gap-2 text-decoration-none">
              <IncrelogLogo size={34} />
              <h6 className="mb-0 f-w-800 text-dark">IncrelogEMS</h6>
            </Link>
            <LanguageSwitcher />
          </div>
          <div className="ems-apply-wrap">
            <div
              className="login-form card"
              style={{ width: "100%", maxWidth: 560, borderRadius: 12, border: "none", boxShadow: "0 10px 40px rgba(36,105,92,0.12)" }}
            >
              <div className="card-body p-4 p-md-5 text-center">
                <span className="ems-stat-icon teal mb-3" style={{ width: 72, height: 72 }}>
                  <IconCheck className="svg-32" />
                </span>
                <h4 className="f-w-700 mb-1">{a.successTitle}</h4>
                <p className="text-muted mb-3">
                  {a.successBody.replace("{name}", done.name)}
                </p>
                <p className="mb-2">
                  <span className="ems-fs-12 text-muted d-block mb-1">{a.referenceLabel}</span>
                  <code className="ems-invoice-badge">{done.reference}</code>
                </p>
                {done.emailSent && (
                  <p className="ems-fs-12 text-success f-w-600 mb-2 d-flex align-items-center justify-content-center gap-1">
                    <IconCheck className="svg-14" />
                    <span>{a.emailSentNote}</span>
                  </p>
                )}
                <Link
                  href={`/track?code=${done.code ?? ""}&ref=${done.reference}`}
                  className="btn btn-soft-secondary btn-sm f-w-700 mb-4"
                >
                  {t.trackPage.trackCta}
                </Link>

                <div className="d-flex justify-content-center gap-2 flex-wrap">
                  <Button variant="secondary" onClick={resetAll}>
                    {a.applyAnother}
                  </Button>
                  <Link href="/">
                    <Button>{t.common.back}</Button>
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="ems-auth-wrapper ems-apply-page">
      <div className="container-fluid py-3">
        <div className="d-flex justify-content-between align-items-center py-2">
          <Link href="/" className="d-flex align-items-center gap-2 text-decoration-none">
            <IncrelogLogo size={34} />
            <h6 className="mb-0 f-w-800 text-dark">IncrelogEMS</h6>
          </Link>
          <LanguageSwitcher />
        </div>

        <div className="ems-apply-wrap">
          <div
            className="login-form card ems-wizard-card"
            style={{ width: "100%", maxWidth: 780, borderRadius: 12, border: "none", boxShadow: "0 10px 40px rgba(36,105,92,0.12)" }}
          >
            <div className="card-body p-3 p-md-4 d-flex flex-column" style={{ gap: 12, minHeight: 0, flex: "1 1 auto" }}>
              <div className="text-center mb-0">
                <h4 className="f-w-700 mb-1">{a.title}</h4>
                <h6 className="text-muted f-w-500">{a.subtitle}</h6>
              </div>

              <AdmissionStepper steps={stepLabels} current={step} onJump={goToStep} stepOf={a.stepOf} />

              {step === 0 ? (
                /* ---------- Step 1: find the institution ---------- */
                <div className="ems-wizard-scroll">
                  <p className="f-w-700 ems-fs-13 mb-3 ems-text-teal">{a.step1Title}</p>
                  <p className="ems-fs-13 text-muted">{a.step1Hint}</p>
                  <div className="row g-2 align-items-end mb-3">
                    <div className="col-12 col-sm-8">
                      <Input
                        label={t.auth.institutionCode}
                        value={code}
                        placeholder="EMS-HS-0001"
                        onChange={(e) => setCode(e.target.value.toUpperCase())}
                        onKeyDown={(e) => e.key === "Enter" && findByCode()}
                      />
                    </div>
                    <div className="col-12 col-sm-4">
                      <Button className="w-100" loading={finding} disabled={!code.trim()} onClick={() => findByCode()}>
                        <IconSearch className="svg-16" />
                        <span className="ms-1">{a.findButton}</span>
                      </Button>
                    </div>
                  </div>

                  <div className="text-center my-3">
                    <span className="ems-fs-12 text-muted">— {a.orLabel} —</span>
                  </div>

                  <div className="row g-2 align-items-end">
                    <div className="col-12 col-sm-8">
                      <Input
                        label={a.searchLabel}
                        value={query}
                        placeholder={a.searchPlaceholder}
                        onChange={(e) => setQuery(e.target.value)}
                        onKeyDown={(e) => e.key === "Enter" && searchByName()}
                      />
                    </div>
                    <div className="col-12 col-sm-4">
                      <Button className="w-100" variant="secondary" loading={searching} disabled={query.trim().length < 2} onClick={searchByName}>
                        <IconSearch className="svg-16" />
                        <span className="ms-1">{t.common.search}</span>
                      </Button>
                    </div>
                  </div>

                  {results !== null && (
                    <div className="mt-3" style={{ maxHeight: 300, overflowY: "auto" }}>
                      {results.length === 0 ? (
                        <Alert type="info">{a.searchEmpty}</Alert>
                      ) : (
                        results.map((inst) => (
                          <button
                            key={inst.code}
                            type="button"
                            className="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
                            onClick={() => { setCode(inst.code); findByCode(inst.code); }}
                          >
                            <span className="min-w-0">
                              <span className="f-w-700 d-block text-truncate">{inst.name}</span>
                              <span className="ems-fs-11 text-muted">
                                {t.types[inst.type as keyof typeof t.types]}
                                {inst.district ? ` · ${inst.district}` : ""}
                                {inst.subDistrict ? ` — ${inst.subDistrict}` : ""}
                              </span>
                            </span>
                            <span className="d-flex align-items-center gap-2 flex-shrink-0">
                              <code className="ems-invoice-badge">{inst.code}</code>
                              <IconArrowRight className="svg-16 text-muted" />
                            </span>
                          </button>
                        ))
                      )}
                    </div>
                  )}

                  <p className="ems-fs-11 text-muted mt-3 mb-0">{a.codeHint}</p>
                </div>
              ) : (
                /* ---------- Steps 2–5: the shared admission wizard ---------- */
                <AdmissionFormWizard
                  classes={institution?.classes ?? []}
                  sessions={institution?.sessions ?? []}
                  values={form}
                  onChange={(v) => setForm((prev) => ({ ...prev, ...v }))}
                  step={step - 1}
                  onStep={(i) => goToStep(i + 1)}
                  hideStepper
                  submitLabel={a.submitButton}
                  submitting={submitting}
                  onSubmit={submit}
                  onBackFirst={() => goToStep(0)}
                  honeypot={{ value: form.company, setValue: (v) => setForm((prev) => ({ ...prev, company: v })) }}
                  extraStep2={
                    /* minimal tracking account — password alongside the details already given */
                    <div className="mt-2" style={{ border: "1px solid #e6edef", borderRadius: 10, padding: "10px 12px 0" }}>
                      <div className="form-check">
                        <input
                          className="form-check-input"
                          type="checkbox"
                          role="switch"
                          id="track-account"
                          checked={wantAccount}
                          onChange={(e) => setWantAccount(e.target.checked)}
                        />
                        <label className="form-check-label f-w-600 ems-fs-13" htmlFor="track-account">
                          {a.accountTitle}
                        </label>
                      </div>
                      {wantAccount && (
                        <>
                          <p className="ems-fs-11 text-muted mb-2 mt-1">{a.accountHint}</p>
                          <Input
                            label={t.common.password}
                            type="password"
                            autoComplete="new-password"
                            value={accountPassword}
                            placeholder="••••••••"
                            onChange={(e) => setAccountPassword(e.target.value)}
                          />
                        </>
                      )}
                    </div>
                  }
                  above={
                    institution ? (
                      <>
                        {/* chosen institution banner */}
                        <div
                          className="d-flex flex-wrap align-items-center justify-content-between gap-2 p-3 mb-3 rounded"
                          style={{ background: "rgba(36,105,92,0.06)" }}
                        >
                          <div className="min-w-0">
                            <p className="ems-fs-11 text-muted mb-0">{a.chosenLabel}</p>
                            <p className="f-w-700 mb-0 text-truncate">
                              {institution.name}
                              {institution.eiin ? <span className="ems-fs-12 text-muted f-w-500"> · EIIN {institution.eiin}</span> : null}
                            </p>
                            <p className="ems-fs-11 text-muted mb-0">
                              <span className={`ems-type-pill ems-type-${institution.type}`}>
                                {t.types[institution.type as keyof typeof t.types]}
                              </span>
                              {" "}
                              {institution.district ? `${institution.district}${institution.subDistrict ? ` — ${institution.subDistrict}` : ""}` : institution.address}
                            </p>
                          </div>
                          <Button size="sm" variant="secondary" onClick={() => goToStep(0)}>
                            {a.changeInstitution}
                          </Button>
                        </div>
                      </>
                    ) : null
                  }
                  reviewTop={
                    institution ? (
                      <div className="mb-3" style={{ border: "1px solid #e6edef", borderRadius: 10, padding: "12px 14px 2px" }}>
                        <p className="f-w-700 ems-fs-13 mb-3 ems-text-teal">{a.stepInstitution}</p>
                        <WizardReviewRow label={a.chosenLabel} value={`${institution.name} (${institution.code})`} />
                        <WizardReviewRow label={t.common.eiin} value={institution.eiin} />
                      </div>
                    ) : null
                  }
                />
              )}
            </div>
          </div>
        </div>

        <p className="text-center ems-fs-13 mb-0 mt-3">
          {t.auth.haveAccount}{" "}
          <Link href="/login" className="ems-text-teal f-w-700 text-decoration-none">
            {t.auth.loginNow}
          </Link>
        </p>
      </div>
    </div>
  );
}
