import { Link } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { Plus, Trash2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { MIN_BOXES, MIN_REFERENCES, UNITS_PER_BOX, wholesaleSchema } from "@/lib/wholesale";

import { Button } from "@/components/ui/button";
type Ref = { name: string; relationship: string; phone: string; email: string };
const emptyRef = (): Ref => ({ name: "", relationship: "", phone: "", email: "" });

function Label({ text, children, required = true }: { text: string; children: React.ReactNode; required?: boolean }) {
  return <label className="block space-y-1 text-sm font-semibold">{text}{required && <span className="text-primary"> *</span>}{children}</label>;
}

export function WholesaleApplicationForm({ embedded = false }: { embedded?: boolean }) {
  const [f, setF] = useState({ application_type: "Wholesale" as "Wholesale" | "Distributor", business_name: "", address: "", contact_person: "", position: "", title: "", website: "", boxes_per_order: MIN_BOXES });
  const [phones, setPhones] = useState([""]);
  const [emails, setEmails] = useState([""]);
  const [refs, setRefs] = useState<Ref[]>([emptyRef(), emptyRef()]);
  const [file, setFile] = useState<File | null>(null);
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    const parsed = wholesaleSchema.safeParse({ ...f, phones: phones.filter((p) => p.trim()), emails: emails.filter((m) => m.trim()), references_list: refs });
    if (!parsed.success) { toast.error(parsed.error.issues[0]?.message ?? "Please check the form."); return; }
    if (!file) { toast.error("Please upload a copy of your business registration."); return; }
    if (file.size > 10 * 1024 * 1024) { toast.error("File must be under 10 MB."); return; }
    if (!/^(application\/pdf|image\/(jpeg|png|webp))$/.test(file.type)) { toast.error("Upload a PDF, JPG, PNG or WebP file."); return; }
    setBusy(true);
    const ext = file.name.split(".").pop()?.toLowerCase().replace(/[^a-z0-9]/g, "") || "pdf";
    const path = `${crypto.randomUUID()}.${ext}`;
    const up = await supabase.storage.from("business-docs").upload(path, file, { contentType: file.type });
    if (up.error) { setBusy(false); toast.error("Couldn't upload your document. Please try again."); return; }
    const { error } = await supabase.from("wholesale_applications").insert({ ...parsed.data, website: parsed.data.website || null, registration_doc_path: path });
    setBusy(false);
    if (error) { toast.error("Couldn't submit your application. Please try again."); return; }
    setDone(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (done) return (
    <div className="mx-auto max-w-xl px-5 py-24 text-center">
      <h2 className="text-3xl font-semibold">Application received 💋</h2>
      <p className="mt-4 text-lg text-muted-foreground">Thank you! Our wholesale team will review your application and contact you by email.</p>
    </div>
  );

  const list = (vals: string[], set: (v: string[]) => void, type: string, ph: string) => (
    <div className="space-y-2">
      {vals.map((v, i) => (
        <div key={i} className="flex gap-2">
          <input className="field" type={type} placeholder={ph} maxLength={255} value={v} onChange={(e) => set(vals.map((x, j) => (j === i ? e.target.value : x)))} />
          {i > 0 && <Button variant="ghost" type="button" onClick={() => set(vals.filter((_, j) => j !== i))} aria-label="Remove" className="text-muted-foreground"><Trash2 className="h-4 w-4" /></Button>}
        </div>
      ))}
      {vals.length < 3 && <Button variant="ghost" type="button" onClick={() => set([...vals, ""])} className="flex items-center gap-1 text-sm font-semibold text-primary"><Plus className="h-4 w-4" />Add another</Button>}
    </div>
  );

  return (
    <div className={embedded ? "mt-12 border-t pt-10" : "mx-auto max-w-4xl px-5 py-12"}>
      <h2 className="text-3xl font-semibold">Wholesale & <em className="text-primary">Distributors</em></h2>
      <p className="mt-3 text-lg text-muted-foreground">Bring Right On Gloss to your store, salon or region. Fill in the application below and our team will be in touch.</p>
      <div className="mt-4 flex flex-wrap gap-4 text-sm font-semibold">
        <Link to="/wholesale-faq" className="text-primary underline">Read the Wholesale FAQ →</Link>
        <Link to="/distributor" className="text-primary underline">Already approved? Place a bulk order →</Link>
      </div>
      <div className="mt-6 grid gap-4 sm:grid-cols-2">
        <div className="rounded-2xl bg-secondary p-5"><p className="text-sm text-muted-foreground">Minimum order</p><p className="text-2xl font-semibold">{MIN_BOXES} boxes</p><p className="text-sm">{UNITS_PER_BOX} glosses per box · {MIN_BOXES * UNITS_PER_BOX} units minimum</p></div>
        <div className="rounded-2xl bg-secondary p-5"><p className="text-sm text-muted-foreground">References</p><p className="text-2xl font-semibold">{MIN_REFERENCES}+ required</p><p className="text-sm">References or guarantors</p></div>
      </div>

      <form onSubmit={submit} className="mt-10 space-y-8">
        <section className="space-y-4 rounded-2xl bg-card p-6">
          <h2 className="text-2xl font-semibold">Business details</h2>
          <div className="flex gap-2">
            {(["Wholesale", "Distributor"] as const).map((t) => (
              <Button variant="ghost" type="button" key={t} onClick={() => setF({ ...f, application_type: t })} className={`rounded-full border px-5 py-2 text-sm font-semibold ${f.application_type === t ? "border-primary bg-primary text-primary-foreground" : "bg-card"}`}>{t}</Button>
            ))}
          </div>
          <Label text="Business name"><input className="field" maxLength={200} value={f.business_name} onChange={(e) => setF({ ...f, business_name: e.target.value })} /></Label>
          <Label text="Business address"><textarea className="field min-h-20" maxLength={500} value={f.address} onChange={(e) => setF({ ...f, address: e.target.value })} /></Label>
          <Label text="Copy of business registration (PDF or image, max 10 MB)"><input className="field" type="file" accept="application/pdf,image/jpeg,image/png,image/webp" onChange={(e) => setFile(e.target.files?.[0] ?? null)} /></Label>
          <Label text="Website" required={false}><input className="field" placeholder="https://" maxLength={255} value={f.website} onChange={(e) => setF({ ...f, website: e.target.value })} /></Label>
        </section>

        <section className="space-y-4 rounded-2xl bg-card p-6">
          <h2 className="text-2xl font-semibold">Contact person</h2>
          <div className="grid gap-4 sm:grid-cols-[120px_1fr_1fr]">
            <Label text="Title"><select className="field" value={f.title} onChange={(e) => setF({ ...f, title: e.target.value })}><option value="">Select</option>{["Mr", "Mrs", "Ms", "Miss", "Dr", "Chief"].map((t) => <option key={t}>{t}</option>)}</select></Label>
            <Label text="Full name"><input className="field" maxLength={120} value={f.contact_person} onChange={(e) => setF({ ...f, contact_person: e.target.value })} /></Label>
            <Label text="Position"><input className="field" placeholder="e.g. Owner, Buyer" maxLength={120} value={f.position} onChange={(e) => setF({ ...f, position: e.target.value })} /></Label>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Label text="Phone numbers">{list(phones, setPhones, "tel", "+1 555 000 0000")}</Label>
            <Label text="Emails">{list(emails, setEmails, "email", "name@business.com")}</Label>
          </div>
        </section>

        <section className="space-y-4 rounded-2xl bg-card p-6">
          <h2 className="text-2xl font-semibold">References or guarantors <span className="text-base font-normal text-muted-foreground">(minimum {MIN_REFERENCES})</span></h2>
          {refs.map((r, i) => (
            <div key={i} className="space-y-3 rounded-xl border p-4">
              <div className="flex items-center justify-between"><p className="font-semibold">Reference {i + 1}</p>
                {i >= MIN_REFERENCES && <Button variant="ghost" type="button" onClick={() => setRefs(refs.filter((_, j) => j !== i))} aria-label="Remove reference" className="text-muted-foreground"><Trash2 className="h-4 w-4" /></Button>}</div>
              <div className="grid gap-3 sm:grid-cols-2">
                {(["name", "relationship", "phone", "email"] as const).map((k) => (
                  <input key={k} className="field" placeholder={{ name: "Full name", relationship: "Relationship (e.g. supplier, bank)", phone: "Phone", email: "Email" }[k]} type={k === "email" ? "email" : k === "phone" ? "tel" : "text"} maxLength={k === "email" ? 255 : 120}
                    value={r[k]} onChange={(e) => setRefs(refs.map((x, j) => (j === i ? { ...x, [k]: e.target.value } : x)))} />
                ))}
              </div>
            </div>
          ))}
          {refs.length < 5 && <Button variant="ghost" type="button" onClick={() => setRefs([...refs, emptyRef()])} className="flex items-center gap-1 text-sm font-semibold text-primary"><Plus className="h-4 w-4" />Add another reference</Button>}
        </section>

        <section className="space-y-4 rounded-2xl bg-card p-6">
          <h2 className="text-2xl font-semibold">Order size</h2>
          <Label text={`Boxes per order (minimum ${MIN_BOXES}, ${UNITS_PER_BOX} glosses per box)`}>
            <input className="field max-w-40" type="number" min={MIN_BOXES} value={f.boxes_per_order} onChange={(e) => setF({ ...f, boxes_per_order: Number(e.target.value) })} />
          </Label>
          <p className="text-sm text-muted-foreground">= {Math.max(0, f.boxes_per_order || 0) * UNITS_PER_BOX} glosses</p>
        </section>

        <Button className="btn-gloss w-full" disabled={busy}>{busy ? "Submitting…" : "Submit application"}</Button>
      </form>
    </div>
  );
}
