import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabaseExt as supabase } from "@/integrations/external-supabase/client";
import { Header } from "@/components/site/Header";
import { Footer } from "@/components/site/Footer";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { useState } from "react";
import { toast } from "sonner";
import { formatBDT } from "@/lib/format";
import { z } from "zod";

const searchSchema = z.object({ qty: z.coerce.number().int().min(1).max(20).default(1) });

export const Route = createFileRoute("/order/$packageId")({
  component: OrderPage,
  validateSearch: searchSchema,
});

function OrderPage() {
  const { packageId } = Route.useParams();
  const { qty: initialQty } = Route.useSearch();
  const navigate = useNavigate();
  const [qty] = useState(initialQty);
  const [email, setEmail] = useState("");
  const [whatsapp, setWhatsapp] = useState("");
  const [paymentMethod, setPaymentMethod] = useState<"bkash" | "nagad">("bkash");
  const [transactionId, setTransactionId] = useState("");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const { data: pkg, isLoading } = useQuery({
    queryKey: ["pkg", packageId],
    queryFn: async () => {
      const { data, error } = await supabase.from("packages").select("*").eq("id", packageId).maybeSingle();
      if (error) throw error;
      return data;
    },
  });

  const totalCredits = pkg ? pkg.credits * qty : 0;
  const totalBdt = pkg ? pkg.price_bdt * qty : 0;

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!pkg) return;
    if (!/^\S+@\S+\.\S+$/.test(email)) { toast.error("Sothik email din"); return; }
    setSubmitting(true);
    try {
      const res = await fetch("/api/public/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          packageId: pkg.id, quantity: qty, customerEmail: email,
          whatsapp: whatsapp || null, paymentMethod, transactionId: transactionId || null, notes: notes || null,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed");
      toast.success("Order pathano hoyeche!");
      navigate({ to: "/order-success/$orderId", params: { orderId: data.orderId } });
    } catch (e: any) {
      toast.error(e.message || "Kichu shomossha hoyeche");
    } finally { setSubmitting(false); }
  }

  if (isLoading) return <div className="min-h-screen flex items-center justify-center text-muted-foreground">Loading...</div>;
  if (!pkg) return (
    <div className="min-h-screen flex flex-col"><Header /><div className="flex-1 flex items-center justify-center p-6">
      <Card className="p-8 text-center max-w-md"><h2 className="text-xl font-bold">Package paowa jayni</h2>
      <Button asChild className="mt-4"><Link to="/">Home e jan</Link></Button></Card></div></div>
  );

  return (
    <div className="min-h-screen flex flex-col bg-background">
      <Header />
      <main className="flex-1 py-10">
        <div className="container max-w-3xl mx-auto px-4">
          <h1 className="text-3xl font-bold tracking-tight mb-2">Order Confirm Korun</h1>
          <p className="text-muted-foreground mb-8">Form ta fill up korun, admin verify korar shathei email e credit pabe.</p>

          <div className="grid md:grid-cols-[1fr_320px] gap-6">
            <Card className="p-6 rounded-2xl">
              <form onSubmit={handleSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="email">Email <span className="text-destructive">*</span></Label>
                  <Input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="apnar@email.com" />
                  <p className="text-xs text-muted-foreground">Ei email e credit deliver hobe</p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="whatsapp">WhatsApp <span className="text-muted-foreground text-xs">(optional)</span></Label>
                  <Input id="whatsapp" value={whatsapp} onChange={(e) => setWhatsapp(e.target.value)} placeholder="+880 1XXX XXXXXX" />
                </div>
                <div className="space-y-2">
                  <Label>Payment Method</Label>
                  <RadioGroup value={paymentMethod} onValueChange={(v) => setPaymentMethod(v as any)} className="grid grid-cols-2 gap-3">
                    <label className={`border rounded-xl p-4 cursor-pointer transition-all ${paymentMethod === "bkash" ? "border-primary bg-primary/5" : "border-border"}`}>
                      <RadioGroupItem value="bkash" className="sr-only" />
                      <div className="font-semibold text-[#e2136e]">bKash</div>
                      <div className="text-xs text-muted-foreground mt-1">Send Money</div>
                    </label>
                    <label className={`border rounded-xl p-4 cursor-pointer transition-all ${paymentMethod === "nagad" ? "border-primary bg-primary/5" : "border-border"}`}>
                      <RadioGroupItem value="nagad" className="sr-only" />
                      <div className="font-semibold text-[#ed1c24]">Nagad</div>
                      <div className="text-xs text-muted-foreground mt-1">Send Money</div>
                    </label>
                  </RadioGroup>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="txn">Transaction ID <span className="text-muted-foreground text-xs">(payment kore thakle)</span></Label>
                  <Input id="txn" value={transactionId} onChange={(e) => setTransactionId(e.target.value)} placeholder="e.g. TXN12345ABC" />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="notes">Notes <span className="text-muted-foreground text-xs">(optional)</span></Label>
                  <Textarea id="notes" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Konota bishesh kotha?" rows={3} />
                </div>
                <Button type="submit" disabled={submitting} className="w-full h-12 rounded-full bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] text-primary-foreground shadow-md text-base font-semibold">
                  {submitting ? "Pathano hocche..." : `Order Pathao — ${formatBDT(totalBdt)}`}
                </Button>
              </form>
            </Card>

            <Card className="p-6 rounded-2xl bg-secondary/30 h-fit sticky top-24">
              <div className="text-sm text-muted-foreground">Order Summary</div>
              <div className="font-semibold mt-1">{pkg.name}</div>
              <div className="text-3xl font-extrabold bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] bg-clip-text text-transparent mt-2">{totalCredits} Credits</div>
              <div className="text-xs text-muted-foreground">({pkg.credits} × {qty})</div>
              <div className="border-t border-border my-4" />
              <div className="flex items-center justify-between text-sm"><span>Price per pack</span><span>{formatBDT(pkg.price_bdt)}</span></div>
              <div className="flex items-center justify-between text-sm mt-1"><span>Quantity</span><span>{qty}</span></div>
              <div className="flex items-center justify-between font-bold text-lg mt-3 pt-3 border-t border-border"><span>Total</span><span>{formatBDT(totalBdt)}</span></div>
            </Card>
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
}