'use client';

import { Suspense, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { API_BASE } from '@/lib/api';

type Info = {
  headline: string;
  benefits: string[];
  steps: string[];
  note?: string;
};
type InfoResponse = {
  types: Record<string, Info>;
  required_documents: Record<string, string[]>;
};

const TYPE_LABELS: Record<string, string> = {
  gym: 'Gym', doctor: 'Doctor', trainer: 'Trainer', dietitian: 'Dietitian',
  pharmacy: 'Pharmacy', store: 'Store', lab: 'Lab', venue: 'Villa / Farmhouse',
};

const DOC_LABELS: Record<string, string> = {
  cnic_front: 'CNIC (front)', cnic_back: 'CNIC (back)', ntn: 'NTN certificate',
  license: 'License', bank_cheque: 'Bank cheque', ownership_proof: 'Ownership proof',
  photo: 'Photo',
};

function PartnerPageInner() {
  const searchParams = useSearchParams();
  const initialType = (() => {
    const t = searchParams.get('type');
    return t && t in TYPE_LABELS ? t : 'gym';
  })();
  const [info, setInfo] = useState<InfoResponse | null>(null);
  const [type, setType] = useState<string>(initialType);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<Record<string, string>>({});
  const [files, setFiles] = useState<Record<string, File | null>>({});

  useEffect(() => {
    fetch(`${API_BASE}/partners/info`)
      .then((r) => r.json())
      .then(setInfo)
      .catch(() => setError('Could not load partner info. Please try again.'));
  }, []);

  const current = info?.types[type];
  const requiredDocs = useMemo(
    () => info?.required_documents[type] ?? [],
    [info, type]
  );

  const set = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      const fd = new FormData();
      fd.append('type', type);
      Object.entries(form).forEach(([k, v]) => v && fd.append(k, v));
      Object.entries(files).forEach(([k, file]) => {
        if (file) fd.append(`documents[${k}]`, file);
      });

      const res = await fetch(`${API_BASE}/partners/apply`, { method: 'POST', body: fd });
      const j = await res.json();
      if (!res.ok) throw new Error(j.message || 'Submission failed');
      setDone(j.message || 'Application received. We will email you once approved.');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Submission failed');
    } finally {
      setSubmitting(false);
    }
  }

  if (done) {
    return (
      <main className="mx-auto max-w-2xl px-4 py-16 text-center">
        <div className="rounded-2xl border border-brand-tint bg-brand-soft p-8">
          <h1 className="text-2xl font-semibold text-brand-dark">Application received</h1>
          <p className="mt-3 text-brand-strong">{done}</p>
        </div>
      </main>
    );
  }

  return (
    <main className="mx-auto max-w-5xl px-4 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-bold">Become a Partner</h1>
        <p className="mt-2 text-muted">
          List your business on Fitorza. Free to join — you only pay when you earn.
        </p>
      </header>

      {/* type selector */}
      <div className="mb-8 flex flex-wrap gap-2">
        {Object.keys(TYPE_LABELS).map((t) => (
          <button
            key={t}
            onClick={() => setType(t)}
            className={`rounded-full px-4 py-2 text-sm font-medium transition ${
              type === t ? 'bg-brand-strong text-white' : 'bg-soft text-ink hover:bg-soft'
            }`}
          >
            {TYPE_LABELS[t]}
          </button>
        ))}
      </div>

      <div className="grid gap-8 md:grid-cols-2">
        {/* info panel */}
        <section>
          {current && (
            <div className="rounded-2xl border border-hair p-6">
              <h2 className="text-xl font-semibold">{current.headline}</h2>
              <ul className="mt-4 space-y-2">
                {current.benefits.map((b) => (
                  <li key={b} className="flex items-start gap-2 text-ink">
                    <span className="mt-1 text-brand-strong">✓</span>
                    <span>{b}</span>
                  </li>
                ))}
              </ul>
              <div className="mt-5">
                <p className="text-sm font-medium text-muted">How it works</p>
                <ol className="mt-2 flex flex-wrap gap-2 text-sm">
                  {current.steps.map((s, i) => (
                    <li key={s} className="rounded-lg bg-soft px-3 py-1">
                      {i + 1}. {s}
                    </li>
                  ))}
                </ol>
              </div>
              {current.note && (
                <p className="mt-4 rounded-lg bg-amber-50 p-3 text-sm text-amber-800">{current.note}</p>
              )}
            </div>
          )}
        </section>

        {/* application form */}
        <section>
          <form onSubmit={submit} className="space-y-4 rounded-2xl border border-hair p-6">
            {error && <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700">{error}</div>}

            <Field label="Full name" required value={form.full_name || ''} onChange={(v) => set('full_name', v)} />
            <Field label="Business name" value={form.business_name || ''} onChange={(v) => set('business_name', v)} />
            <div className="grid grid-cols-2 gap-3">
              <Field label="Email" type="email" required value={form.email || ''} onChange={(v) => set('email', v)} />
              <Field label="Phone" required value={form.phone || ''} onChange={(v) => set('phone', v)} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="City" value={form.city || ''} onChange={(v) => set('city', v)} />
              <div>
                <label className="mb-1 block text-sm font-medium text-ink">Account type</label>
                <select
                  className="w-full rounded-lg border border-hair px-3 py-2"
                  value={form.account_kind || 'individual'}
                  onChange={(e) => set('account_kind', e.target.value)}
                >
                  <option value="individual">Individual</option>
                  <option value="business">Business</option>
                </select>
              </div>
            </div>
            <Field label="Address" value={form.address || ''} onChange={(v) => set('address', v)} />
            <div className="grid grid-cols-2 gap-3">
              <Field label="CNIC" value={form.cnic || ''} onChange={(v) => set('cnic', v)} />
              <Field label="NTN" value={form.ntn || ''} onChange={(v) => set('ntn', v)} />
            </div>
            {(type === 'pharmacy' || type === 'lab' || type === 'doctor' || type === 'dietitian') && (
              <Field label="License number" value={form.license_number || ''} onChange={(v) => set('license_number', v)} />
            )}

            {/* required documents */}
            <div>
              <p className="mb-2 text-sm font-medium text-ink">Required documents</p>
              <div className="space-y-2">
                {requiredDocs.map((doc) => (
                  <div key={doc} className="flex items-center justify-between gap-3 rounded-lg border border-hair px-3 py-2">
                    <span className="text-sm text-ink">{DOC_LABELS[doc] ?? doc}</span>
                    <input
                      type="file"
                      accept=".jpg,.jpeg,.png,.pdf"
                      className="text-sm"
                      onChange={(e) => setFiles((f) => ({ ...f, [doc]: e.target.files?.[0] ?? null }))}
                    />
                  </div>
                ))}
              </div>
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="w-full rounded-lg bg-brand-strong py-3 font-medium text-white hover:bg-brand-dark disabled:opacity-50"
            >
              {submitting ? 'Submitting…' : 'Submit application'}
            </button>
            <p className="text-center text-xs text-muted">
              We review applications and email your login once approved.
            </p>
          </form>
        </section>
      </div>
    </main>
  );
}

function Field({
  label, value, onChange, type = 'text', required = false,
}: {
  label: string; value: string; onChange: (v: string) => void; type?: string; required?: boolean;
}) {
  return (
    <div>
      <label className="mb-1 block text-sm font-medium text-ink">
        {label} {required && <span className="text-red-500">*</span>}
      </label>
      <input
        type={type}
        required={required}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="w-full rounded-lg border border-hair px-3 py-2 outline-none focus:border-brand-strong"
      />
    </div>
  );
}

export default function PartnerPage() {
  return (
    <Suspense fallback={<div className="mx-auto max-w-5xl px-4 py-10 text-muted">Loading…</div>}>
      <PartnerPageInner />
    </Suspense>
  );
}
