"use client";
import React, { Suspense } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { useSearchParams, useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { CheckCircle2 } from "lucide-react";

type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'; label: string; isRequired?: boolean; helpText?: string|null };

function RegistrationSuccessContent() {
  const search = useSearchParams();
  const router = useRouter();
  const { token } = useAuth();
  const registrationId = search.get("registrationId") || search.get("id");
  const fallbackTotalParam = search.get("totalDue");
  const fallbackTotalDue = React.useMemo(() => {
    const n = fallbackTotalParam ? Number(fallbackTotalParam) : 0;
    return isNaN(n) ? 0 : n;
  }, [fallbackTotalParam]);

  const [reg, setReg] = React.useState<any | null>(null);
  const [form, setForm] = React.useState<{ isRequired: boolean; fields: FormField[] } | null>(null);
  const [formsData, setFormsData] = React.useState<Record<number, Record<string, string>>>({});
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [info, setInfo] = React.useState<string | null>(null);
  const [payLoading, setPayLoading] = React.useState(false);

  React.useEffect(() => {
    (async () => {
      setError(null);
      setInfo(null);
      if (!registrationId) return;
      try {
        setLoading(true);
        // Try to fetch registration and event form
        const r = token ? await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }) : null;
        if (r) {
          setReg(r);
          const ev = await (await import('@/lib/api')).apiFetch(`/api/events/${encodeURIComponent(r.eventId)}`);
          if (ev?.form) setForm(ev.form);
          // Load any saved draft
          try {
            const d = await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token || undefined });
            if (d && d.data && typeof d.data === 'object') setFormsData(d.data);
          } catch {}
        }
      } catch (e: any) {
        setError(e?.message || 'Failed to load details');
      } finally {
        setLoading(false);
      }
    })();
  }, [registrationId, token]);

  const totalDue = React.useMemo(() => {
    if (!reg) return 0;
    // Backend attaches a tranche-aware totalDueComputed (exact even when a line spans
    // multiple early-bird prices) — fall back to the old client-side estimate otherwise.
    if (reg.totalDueComputed !== null && reg.totalDueComputed !== undefined) return reg.totalDueComputed;
    try {
      return (reg.registrationOptions || []).reduce((s: number, ro: any) => {
        const unit = (ro.priceSnapshot !== null && ro.priceSnapshot !== undefined)
          ? Number(ro.priceSnapshot)
          : (ro.variant?.price ?? ro.eventOption?.price ?? 0);
        return s + unit * (ro.quantity || 0);
      }, 0);
    } catch { return 0; }
  }, [reg]);

  React.useEffect(() => {
    // If free registration, do not show Yoco and redirect to dashboard after a short delay
    if (reg && totalDue === 0) {
      // attempt ticket generation if status is paid (may fail if required forms aren't completed)
      (async () => {
        try {
          if (token && reg?.id) {
            await (await import('@/lib/api')).apiFetch('/api/tickets/generate', { method: 'POST', authToken: token, body: { registrationId: reg.id } });
          }
        } catch {}
        setTimeout(() => router.replace('/dashboard'), 600);
      })();
    }
  }, [reg, totalDue, router, token]);

  const goPay = async () => {
    if (!registrationId) return;
    if (!token) { setError('Please login to pay.'); return; }
    try {
      setError(null);
      setPayLoading(true);
      const { createFullPaymentCheckout } = await import('@/lib/api');
      const res = await createFullPaymentCheckout(token, registrationId);
      if (res.priceUpdated) {
        // Early-bird price changed since registration — surface the new total and
        // reload the registration so the displayed totalDue reflects it, instead of redirecting.
        setError(`${res.message || 'Pricing has changed.'} New total: R ${(res.newTotal ?? 0).toFixed(2)}. Please try again.`);
        try {
          const r = await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
          if (r) setReg(r);
        } catch {}
        return;
      }
      if (!res.redirectUrl) { setError('Failed to create checkout'); return; }
      window.location.href = res.redirectUrl;
    } catch (e: any) {
      setError(e?.message || 'Failed to create checkout');
    } finally {
      setPayLoading(false);
    }
  };

  const goDashboard = () => {
    router.push("/dashboard/user");
  };

  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      <main className="flex-1 px-4 py-10 max-w-2xl mx-auto w-full">
        <div className="border rounded-xl p-6 bg-white shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="w-10 h-10 rounded-xl bg-green-50 flex items-center justify-center shrink-0">
              <CheckCircle2 className="w-5 h-5 text-green-600" />
            </div>
            <h1 className="text-2xl font-semibold text-gray-900">Registration successful</h1>
          </div>
          <p className="text-gray-700 mb-4">Thank you! Your registration has been created{registrationId ? ` (#${registrationId.slice(0,8)})` : ""}.</p>
          {form?.isRequired && reg ? (
            <div className="mb-6 p-3 border rounded bg-yellow-50 text-yellow-800">
              <div className="font-medium">This event requires attendee details.</div>
              <div className="text-sm">Please complete one form per main ticket to receive tickets. You can also do this later from your dashboard, but tickets cannot be generated until completed.</div>
            </div>
          ) : (totalDue > 0 || (!reg && fallbackTotalDue > 0)) ? (
            <p className="text-gray-700 mb-6">Would you like to pay with Yoco now?</p>
          ) : null}

          <div className="flex flex-col sm:flex-row gap-3 mt-4">
            {(totalDue > 0 || (!reg && fallbackTotalDue > 0)) && (
              <button
                onClick={goPay}
                disabled={!registrationId || payLoading}
                className="px-4 py-2 rounded bg-green-600 text-white disabled:opacity-60"
              >{payLoading ? "Creating checkout..." : "Pay with Yoco"}</button>
            )}
            <button
              onClick={goDashboard}
              className="px-4 py-2 rounded bg-gray-100 text-gray-800 hover:bg-gray-200"
            >{(totalDue > 0 || (!reg && fallbackTotalDue > 0)) ? "Go to Dashboard (Pay Later)" : "Go to Dashboard"}</button>
          </div>
          {error && <p className="text-sm text-red-600 mt-3">{error}</p>}
          {!registrationId && (
            <p className="text-sm text-red-600 mt-4">Missing registration reference. You can still go to your Dashboard to view registrations.</p>
          )}
        </div>
      </main>
      <Footer />
    </div>
  );
}

function AttendeeForms({ reg, form, formsData, setFormsData, setError, setInfo }: { reg: any; form: { isRequired: boolean; fields: FormField[] }; formsData: Record<number, Record<string,string>>; setFormsData: any; setError: any; setInfo: any; }) {
  const { token } = useAuth();
  const registrationId = reg?.id;
  const mainTickets = (reg?.registrationOptions || []).filter((o: any) => o?.eventOption?.isMainTicket).reduce((s: number, o: any) => s + (o.quantity || 0), 0);
  const count = Math.max(0, mainTickets);

  const canSubmit = React.useMemo(() => {
    if (!form || count <= 0) return false;
    const reqFields = (form.fields || [])
      .filter(f => !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph')
      .map(f => f.id);
    for (let i = 0; i < count; i++) {
      const data = formsData[i] || {};
      for (const fid of reqFields) {
        const v = data[fid];
        if (v === undefined || v === null || String(v).trim() === '') {
          return false;
        }
      }
    }
    return true;
  }, [form, formsData, count]);

  const update = (idx: number, fieldId: string, value: string) => {
    setFormsData((prev: any) => ({ ...prev, [idx]: { ...(prev[idx]||{}), [fieldId]: value } }));
  };

  const submit = async () => {
    try {
      setError(null); setInfo(null);
      if (!token) { setError('Please login to submit forms.'); return; }
      const payload = [] as any[];
      for (let i = 0; i < count; i++) {
        payload.push({ answers: formsData[i] || {} });
      }
      await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, {
        method: 'POST',
        authToken: token,
        body: { responses: payload }
      });
      setInfo('Attendee forms submitted. You will receive tickets once payment is confirmed.');
    } catch (e: any) {
      setError(e?.message || 'Failed to submit forms');
    }
  };

  const saveDraft = async () => {
    try {
      setError(null); setInfo(null);
      if (!token) { setError('Please login to save drafts.'); return; }
      await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, {
        method: 'PUT',
        authToken: token,
        body: { data: formsData }
      });
      setInfo('Draft saved. You can finish later from your dashboard.');
    } catch (e: any) {
      setError(e?.message || 'Failed to save draft');
    }
  };

  if (!form || !Array.isArray(form.fields) || count === 0) return null;

  return (
    <div className="border rounded p-3 bg-gray-50 mb-4">
      <div className="text-sm font-medium mb-2">Attendee details</div>
      <div className="space-y-4">
        {Array.from({ length: count }, (_, idx) => (
          <div key={idx} className="bg-white border rounded p-3">
            <div className="font-medium mb-2">Attendee {idx + 1}</div>
            {form.fields.map((f) => (
              <div key={f.id} className="mb-2">
                {f.type === 'statement' ? (
                  <div className="text-sm text-gray-700 whitespace-pre-line">{f.label}</div>
                ) : f.type === 'paragraph' ? (
                  <div className="text-sm text-gray-700">
                    {f.label && <div className="font-medium mb-1 whitespace-pre-line">{f.label}</div>}
                    {f.helpText && <div className="whitespace-pre-line">{f.helpText}</div>}
                  </div>
                ) : (
                  <>
                    <label className="block text-xs text-gray-600 mb-1">{f.label}{f.isRequired ? ' *' : ''}</label>
                    {f.type === 'yes_no' ? (
                      <select className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)}>
                        <option value="">Select</option>
                        <option value="yes">Yes</option>
                        <option value="no">No</option>
                      </select>
                    ) : f.type === 'date' ? (
                      <input type="date" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
                    ) : f.type === 'numeric' ? (
                      <input type="number" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
                    ) : (
                      <input type="text" className="border rounded px-2 py-1 text-sm w-full" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
                    )}
                    {f.helpText && <div className="text-xs text-gray-500 mt-1">{f.helpText}</div>}
                  </>
                )}
              </div>
            ))}
          </div>
        ))}
      </div>
      <div className="mt-3 flex gap-2">
        <button className="px-3 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50" disabled={!canSubmit} onClick={submit}>Submit attendee forms</button>
        <button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200" onClick={saveDraft}>Save for later</button>
      </div>
    </div>
  );
}

export default function RegistrationSuccessPage() {
  return (
    <Suspense fallback={<div className="p-6">Loading...</div>}>
      <RegistrationSuccessContent />
    </Suspense>
  );
}
