"use client";

import { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
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 { useCart, type CartLine } from "@/components/shop/cart-context";
import { useAuthModal } from "@/components/shop/auth-modal-context";
import { usePublicSession } from "@/components/shop/public-session-context";
import { clearBuyNowLine, readBuyNowLine } from "@/lib/buy-now";
import { resolvePublicMediaUrl } from "@/lib/public-product";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";

function lineVariantText(line: CartLine): string {
  return Object.entries(line.variantSelections || {})
    .map(([k, v]) => `${k}: ${v}`)
    .join(" · ");
}

export default function CheckoutPayPage() {
  const router = useRouter();
  const search = useSearchParams();
  const source = search.get("source");
  const { lines, clearCart } = useCart();
  const { openAuthModal } = useAuthModal();
  const { isAuthenticated, user } = usePublicSession();
  const [submitting, setSubmitting] = useState(false);
  const [buyNowLine, setBuyNowLine] = useState<CartLine | null>(null);
  const [form, setForm] = useState({
    fullName: "",
    phone: "",
    email: "",
    address: "",
  });

  useEffect(() => {
    setForm((f) => ({
      ...f,
      fullName: f.fullName || [user?.firstName, user?.lastName].filter(Boolean).join(" "),
      email: f.email || user?.email || "",
    }));
  }, [user]);

  useEffect(() => {
    if (source === "buy-now") {
      const line = readBuyNowLine();
      if (line) {
        setBuyNowLine({ ...line, key: `buy-now::${line.productId}` });
      } else {
        setBuyNowLine(null);
      }
      return;
    }
    setBuyNowLine(null);
  }, [source]);

  const orderLines = useMemo(() => {
    if (source === "buy-now") return buyNowLine ? [buyNowLine] : [];
    return lines;
  }, [source, buyNowLine, lines]);

  const totals = useMemo(() => {
    let sub = 0;
    let ship = 0;
    for (const l of orderLines) {
      sub += l.unitPrice * l.quantity;
      ship += (l.shippingPerUnit || 0) * l.quantity;
    }
    return { subtotal: sub, shipping: ship, grand: sub + ship };
  }, [orderLines]);

  const placeOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isAuthenticated) {
      openAuthModal("login");
      return;
    }
    if (orderLines.length === 0) {
      toast.error("No product selected");
      return;
    }
    if (!form.fullName.trim() || !form.phone.trim() || !form.address.trim()) {
      toast.error("Full name, phone and address are required");
      return;
    }

    setSubmitting(true);
    try {
      await DataService.post("/user/shop/orders", {
        items: orderLines.map((l) => ({
          productId: l.productId,
          quantity: l.quantity,
          variantSelections: l.variantSelections,
        })),
        shipping: {
          fullName: form.fullName.trim(),
          phone: form.phone.trim(),
          email: form.email.trim(),
          address: form.address.trim(),
        },
        paymentMethod: "cod",
      });
      toast.success("Order placed successfully");
      if (source === "buy-now") {
        clearBuyNowLine();
      } else {
        clearCart();
      }
      router.push("/account/orders");
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not place order"));
    } finally {
      setSubmitting(false);
    }
  };

  if (orderLines.length === 0) {
    return (
      <div className="container max-w-2xl py-16 text-center">
        <h1 className="text-2xl font-bold text-slate-900">Pay</h1>
        <p className="mt-4 text-gray-600">No item selected for payment.</p>
        <Button asChild className="mt-6">
          <Link href="/checkout">Back to checkout</Link>
        </Button>
      </div>
    );
  }

  return (
    <div className="container max-w-5xl py-10">
      <h1 className="text-3xl font-bold text-slate-900">Pay & place order</h1>
      <div className="mt-8 grid gap-8 lg:grid-cols-2">
        <div className="rounded-md border bg-white p-5">
          <h2 className="font-semibold text-slate-900">Your details</h2>
          <form onSubmit={placeOrder} className="mt-4 space-y-4">
            <div className="grid gap-2">
              <Label htmlFor="fullName">Full name *</Label>
              <Input
                id="fullName"
                value={form.fullName}
                onChange={(e) => setForm((f) => ({ ...f, fullName: e.target.value }))}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="phone">Phone *</Label>
              <Input
                id="phone"
                type="tel"
                value={form.phone}
                onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="email">Email (optional)</Label>
              <Input
                id="email"
                type="email"
                value={form.email}
                onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="address">Address *</Label>
              <Textarea
                id="address"
                rows={4}
                value={form.address}
                onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))}
                required
              />
            </div>
            <p className="rounded-md bg-slate-50 p-3 text-sm text-gray-700">
              <strong>Payment:</strong> COD only.
            </p>
            <Button type="submit" size="lg" className="w-full" disabled={submitting}>
              {submitting ? "Placing order…" : "Pay & place order"}
            </Button>
          </form>
        </div>

        <div className="rounded-md border bg-white p-5">
          <h2 className="font-semibold text-slate-900">Products</h2>
          <ul className="mt-4 space-y-3">
            {orderLines.map((l) => {
              const img = resolvePublicMediaUrl(l.image);
              return (
                <li key={l.key} className="flex items-center gap-3 rounded border p-2">
                  <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded bg-gray-100">
                    {img ? <Image src={img} alt="" fill className="object-cover" sizes="56px" /> : null}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-slate-900">{l.title}</p>
                    {Object.keys(l.variantSelections || {}).length > 0 ? (
                      <p className="truncate text-xs text-gray-500">{lineVariantText(l)}</p>
                    ) : null}
                    <p className="text-xs text-gray-600">Qty: {l.quantity}</p>
                  </div>
                  <p className="text-sm font-semibold text-slate-900">
                    {(l.unitPrice * l.quantity).toFixed(2)}
                  </p>
                </li>
              );
            })}
          </ul>
          <div className="mt-5 space-y-1 border-t pt-4 text-sm">
            <div className="flex justify-between">
              <span>Subtotal</span>
              <span>{totals.subtotal.toFixed(2)}</span>
            </div>
            <div className="flex justify-between">
              <span>Shipping</span>
              <span>{totals.shipping.toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-base font-bold">
              <span>Total</span>
              <span>{totals.grand.toFixed(2)}</span>
            </div>
          </div>
          <p className="mt-3 text-xs text-gray-500">Products are locked on this page (no add/remove/edit).</p>
        </div>
      </div>
    </div>
  );
}
