import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { Copy, CheckCircle2, ArrowLeft } from "lucide-react";
import { Link } from "@tanstack/react-router";
import { toast } from "sonner";

import { getLandingData } from "@/lib/course.functions";
import { submitPayment } from "@/lib/payment.functions";
import { Header } from "@/components/Header";
import { supabase } from "@/integrations/supabase/client";
import { trackEvent } from "@/lib/pixels";
import { useEffect } from "react";

const landingQuery = queryOptions({ queryKey: ["landing"], queryFn: () => getLandingData() });

export const Route = createFileRoute("/buy")({
  loader: ({ context }) => context.queryClient.ensureQueryData(landingQuery),
  component: BuyPage,
});

function BuyPage() {
  const { data } = useSuspenseQuery(landingQuery);
  const navigate = useNavigate();
  const submitFn = useServerFn(submitPayment);
  const { course, settings } = data;
  const [step, setStep] = useState<1 | 2>(1);
  const [loading, setLoading] = useState(false);
  const [copied, setCopied] = useState(false);
  const [form, setForm] = useState({ fullName: "", email: "", phone: "", senderNumber: "", transactionId: "" });

  const courseId = data.course?.id;
  const price = Number(data.course?.discount_price ?? data.course?.price ?? 0);
  useEffect(() => { if (courseId) trackEvent("InitiateCheckout", { content_name: data.course?.title, value: price, currency: "BDT" }); }, [courseId]);

  if (!course || !settings) return <div className="grid min-h-screen place-items-center">No course available.</div>;

  const copy = async () => {
    await navigator.clipboard.writeText(settings.bkash_number);
    setCopied(true);
    toast.success("bKash number copied");
    setTimeout(() => setCopied(false), 2000);
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const { data: auth } = await supabase.auth.getUser();
      if (!auth.user) {
        toast.info("Please sign in to complete payment");
        navigate({ to: "/auth", search: { redirect: "/buy" } });
        return;
      }
      await submitFn({ data: { courseId: course.id, ...form } });
      trackEvent("Lead", { content_name: course.title, value: price, currency: "BDT" });
      trackEvent("AddPaymentInfo", { content_name: course.title, value: price, currency: "BDT" });
      toast.success("Payment submitted! Admin will approve shortly.");
      navigate({ to: "/dashboard", replace: true });
    } catch (err: any) {
      toast.error(err.message ?? "Submission failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen">
      <Header />
      <div className="mx-auto max-w-2xl px-4 py-8">
        <Link to="/" className="mb-6 inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground">
          <ArrowLeft className="h-4 w-4" /> Back
        </Link>

        <div className="rounded-2xl border border-border bg-card p-6 shadow-card md:p-8">
          <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Step {step} of 2
          </div>
          <h1 className="mt-2 font-display text-2xl font-bold md:text-3xl">
            {step === 1 ? "Send Payment via bKash" : "Submit Transaction ID"}
          </h1>

          <div className="mt-6 rounded-xl border border-primary/30 bg-primary/5 p-4">
            <p className="text-sm text-muted-foreground">Amount to pay</p>
            <p className="font-display text-3xl font-bold text-gradient-gold">৳{price.toLocaleString("en-BD")}</p>
            <p className="mt-1 text-xs text-muted-foreground">{course.title}</p>
          </div>

          {step === 1 ? (
            <>
              <div className="mt-6 space-y-4">
                <div>
                  <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">bKash Number ({settings.bkash_account_type})</p>
                  <div className="mt-2 flex items-center gap-2 rounded-lg border border-border bg-input p-3">
                    <span className="flex-1 font-mono text-lg font-semibold">{settings.bkash_number}</span>
                    <button onClick={copy} className="inline-flex items-center gap-1 rounded-md bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground">
                      {copied ? <><CheckCircle2 className="h-3.5 w-3.5" /> Copied</> : <><Copy className="h-3.5 w-3.5" /> Copy</>}
                    </button>
                  </div>
                </div>

                <div className="rounded-lg bg-muted/50 p-4 text-sm">
                  <p className="font-semibold text-foreground">How to pay:</p>
                  <p className="mt-1 whitespace-pre-line text-muted-foreground">{settings.bkash_instructions}</p>
                </div>
              </div>

              <button onClick={() => setStep(2)} className="mt-6 w-full rounded-xl bg-gradient-primary px-6 py-3.5 font-semibold text-primary-foreground shadow-glow">
                I've Paid — Submit Transaction ID
              </button>
            </>
          ) : (
            <form onSubmit={onSubmit} className="mt-6 space-y-4">
              <Field label="Full name" value={form.fullName} onChange={(v) => setForm({ ...form, fullName: v })} required />
              <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} required />
              <Field label="Phone" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} required />
              <Field label="bKash Sender Number (the one you paid from)" value={form.senderNumber} onChange={(v) => setForm({ ...form, senderNumber: v })} required />
              <Field label="bKash Transaction ID (TrxID)" value={form.transactionId} onChange={(v) => setForm({ ...form, transactionId: v })} required />
              <div className="flex gap-3">
                <button type="button" onClick={() => setStep(1)} className="flex-1 rounded-xl border border-border bg-card px-4 py-3 text-sm font-semibold hover:bg-muted">Back</button>
                <button disabled={loading} className="flex-[2] rounded-xl bg-gradient-primary px-4 py-3 text-sm font-semibold text-primary-foreground shadow-glow disabled:opacity-60">
                  {loading ? "Submitting…" : "Submit Payment"}
                </button>
              </div>
              <p className="text-center text-xs text-muted-foreground">Admin reviews payments within 1-3 hours. You'll get access once approved.</p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ label, type = "text", value, onChange, required }: { label: string; type?: string; value: string; onChange: (v: string) => void; required?: boolean }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <input type={type} value={value} onChange={(e) => onChange(e.target.value)} required={required}
        className="mt-1.5 block w-full rounded-lg border border-border bg-input px-3 py-2.5 text-sm outline-none ring-primary/40 focus:ring-2" />
    </label>
  );
}
