"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import CheckoutShippingForm, {
  INITIAL_SHIPPING,
  type ShippingFormFields,
  type ShippingFieldErrors,
} from "@/components/checkout/CheckoutShippingForm";
import PaymentMethod from "@/components/checkout/PaymentMethod";
import { createOrder, getCheckoutPreview } from "@/lib/actions/checkout";
import type { AddressInput } from "@/lib/actions/addresses";

type CartItem = {
  id: string;
  productId: string;
  name: string;
  slug: string;
  details: string;
  quantity: number;
  price: number;
  image: string;
  stockQuantity: number;
  maxQuantity: number;
  inStock: boolean;
  taxRate: number;
};

type Cart = {
  id: string;
  items: CartItem[];
  subtotal: number;
} | null;

type PaymentMethodRow = {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
};

type Summary = {
  subtotal: number;
  discount: number;
  shippingCost: number;
  tax: number;
  total: number;
};

function CheckIcon() {
  return (
    <svg
      className="mt-0.5 h-4 w-4 shrink-0"
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24"
    >
      <path
        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="2"
      />
    </svg>
  );
}

export default function CheckoutPageClient({
  cart,
  paymentMethods,
  initialSummary,
  defaultAddress,
}: {
  cart: Cart;
  paymentMethods: PaymentMethodRow[];
  initialSummary?: Summary;
  defaultAddress?: AddressInput | null;
}) {
  const router = useRouter();
  const items = useMemo(() => cart?.items ?? [], [cart?.items]);
  const subtotal = cart?.subtotal ?? 0;

  const [summary, setSummary] = useState<Summary>(
    initialSummary ?? {
      subtotal,
      discount: 0,
      shippingCost: 0,
      tax: 0,
      total: subtotal,
    },
  );
  const [couponCode, setCouponCode] = useState("");
  const [appliedCoupon, setAppliedCoupon] = useState<string | null>(null);
  const [couponMessage, setCouponMessage] = useState<{
    kind: "success" | "error";
    text: string;
  } | null>(null);
  const [couponBusy, setCouponBusy] = useState(false);

  const [shipping, setShipping] = useState<ShippingFormFields>(() => {
    if (!defaultAddress) return INITIAL_SHIPPING;
    const [firstName, ...lastParts] = defaultAddress.recipientName.split(" ");
    return {
      ...INITIAL_SHIPPING,
      firstName,
      lastName: lastParts.join(" "),
      address: defaultAddress.address,
      city: defaultAddress.city ?? "",
      postalCode: defaultAddress.postalCode ?? "",
      district: defaultAddress.district,
      upazila: defaultAddress.upazila,
    };
  });
  const [fieldErrors, setFieldErrors] = useState<ShippingFieldErrors>({});
  const [payment, setPayment] = useState("cod");
  const [transactionId, setTransactionId] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const enabledMethods = paymentMethods.filter((m) => m.enabled);

  useEffect(() => {
    if (!shipping.district || items.length === 0) return;
    void getCheckoutPreview(
      items.map((i) => ({ productId: i.productId, quantity: i.quantity })),
      appliedCoupon ?? undefined,
      shipping.district,
    ).then((res) => {
      if (res.ok)
        setSummary({
          subtotal: res.data.subtotal,
          discount: res.data.discount,
          shippingCost: res.data.shippingCost,
          tax: res.data.tax,
          total: res.data.grandTotal,
        });
    });
  }, [shipping.district, appliedCoupon, items]);

  async function handleApplyCoupon() {
    const code = couponCode.trim();
    if (!code) return;
    setCouponBusy(true);
    setCouponMessage(null);
    const res = await getCheckoutPreview(
      items.map((i) => ({ productId: i.productId, quantity: i.quantity })),
      code,
      shipping.district,
    );
    setCouponBusy(false);
    if (!res.ok) {
      setCouponMessage({ kind: "error", text: res.error });
      setAppliedCoupon(null);
      return;
    }
    const d = res.data;
    setSummary({
      subtotal: d.subtotal,
      discount: d.discount,
      shippingCost: d.shippingCost,
      tax: d.tax,
      total: d.grandTotal,
    });
    setAppliedCoupon(d.couponCode ?? code.toUpperCase());
    setCouponMessage({
      kind: "success",
      text: `Coupon ${d.couponCode ?? code.toUpperCase()} applied — ${d.discount.toLocaleString()} discount.`,
    });
  }

  async function handlePlaceOrder() {
    if (items.length === 0) return;
    const nextErrors: ShippingFieldErrors = {};
    if (!shipping.firstName.trim())
      nextErrors.firstName = "First name is required.";
    if (!shipping.lastName.trim())
      nextErrors.lastName = "Last name is required.";
    if (!shipping.address.trim()) nextErrors.address = "Address is required.";
    if (!shipping.district) nextErrors.district = "Select a district.";
    if (!shipping.upazila) nextErrors.upazila = "Select a thana / upazila.";
    if (!/^01\d{9}$/.test(shipping.phone.trim()))
      nextErrors.phone = "Enter a valid 11-digit Bangladesh phone number.";
    if (!/^\S+@\S+\.\S+$/.test(shipping.email.trim()))
      nextErrors.email = "Enter a valid email address.";
    setFieldErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setError("Please correct the highlighted fields.");
      return;
    }
    setSubmitting(true);
    setError(null);

    const recipientName = `${shipping.firstName} ${shipping.lastName}`.trim();
    const res = await createOrder({
      source: "WEB",
      customer: {
        name: recipientName,
        email: shipping.email,
        phone: shipping.phone,
      },
      items: items.map((i) => ({
        productId: i.productId,
        quantity: i.quantity,
      })),
      shipping: {
        recipientName,
        address: shipping.address,
        city: shipping.city || undefined,
        upazila: shipping.upazila || undefined,
        district: shipping.district,
        postalCode: shipping.postalCode || undefined,
        country: "Bangladesh",
      },
      billing: {
        recipientName,
        address: shipping.address,
        city: shipping.city || undefined,
        upazila: shipping.upazila || undefined,
        district: shipping.district,
        postalCode: shipping.postalCode || undefined,
        country: "Bangladesh",
      },
      payment: {
        method: payment,
        status: "pending",
        transactionId: transactionId.trim() || undefined,
      },
      couponCode: appliedCoupon ?? undefined,
      notes: shipping.comment || undefined,
    });

    setSubmitting(false);
    if (!res.ok) {
      setError(res.error);
      return;
    }
    if (!res.data) {
      setError("Could not confirm the order. Please try again.");
      return;
    }
    router.push(`/orders/${res.data.orderId}`);
  }

  return (
    <div className="min-h-screen">
      <main className="mx-auto w-full">
        <div className="my-8">
          <h2 className="text-2xl font-bold">Checkout</h2>
          <p className="mb-2 font-body-md text-body-md text-on-surface-variant">
            Review your order summary and proceed to complete your purchase.
          </p>
        </div>

        {items.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16">
            <p className="text-lg font-medium text-foreground mb-2">
              Your cart is empty
            </p>
            <p className="mb-4 max-w-sm text-center text-sm text-muted-foreground">
              Add items to your cart before checking out. Browse the catalogue
              and find what you need.
            </p>
            <Link href="/products">
              <Button>Browse Products</Button>
            </Link>
          </div>
        ) : (
          <div className="flex flex-col gap-8 lg:flex-row">
            <div className="flex-1">
              <CheckoutShippingForm
                values={shipping}
                onChange={(values) => {
                  setShipping(values);
                  setFieldErrors({});
                  setError(null);
                }}
                errors={fieldErrors}
              />
            </div>
            <aside className="w-full shrink-0 lg:w-96">
              <div className="rounded-[18px] border border-[#d6d6d6] p-6">
                <h2 className="mb-6 text-[1.05rem] font-bold">Order Summary</h2>

                {/* Items */}
                <div className="mb-4 space-y-3">
                  {items.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-center justify-between text-sm"
                    >
                      <span className="text-[#626262] truncate mr-2">
                        {item.name} x{item.quantity}
                      </span>
                      <span className="font-bold whitespace-nowrap">
                        ৳{(item.price * item.quantity).toLocaleString()}
                      </span>
                    </div>
                  ))}
                </div>

                {/* Coupon */}
                <div className="mb-4">
                  <label
                    htmlFor="coupon"
                    className="mb-1 block text-xs font-medium text-[#626262]"
                  >
                    Coupon code
                  </label>
                  <div className="flex gap-2">
                    <Input
                      id="coupon"
                      value={couponCode}
                      onChange={(e) =>
                        setCouponCode(e.target.value.toUpperCase())
                      }
                      placeholder="e.g. WELCOME10"
                      className="h-9 uppercase"
                      disabled={couponBusy}
                    />
                    <Button
                      variant="outline"
                      className="h-9 shrink-0"
                      onClick={handleApplyCoupon}
                      disabled={couponBusy || !couponCode.trim()}
                    >
                      Apply
                    </Button>
                  </div>
                  {couponMessage && (
                    <p
                      className={`mt-1 text-xs ${
                        couponMessage.kind === "success"
                          ? "text-green-600"
                          : "text-red-600"
                      }`}
                    >
                      {couponMessage.text}
                    </p>
                  )}
                </div>

                <div className="mb-4 space-y-4 text-sm border-t border-[#d6d6d6] pt-4">
                  <div className="flex justify-between">
                    <span className="text-[#626262]">Sub Total</span>
                    <span className="font-bold">
                      ৳{summary.subtotal.toLocaleString()}
                    </span>
                  </div>
                  {summary.discount > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>Discount</span>
                      <span className="font-bold">
                        − ৳{summary.discount.toLocaleString()}
                      </span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span className="text-[#626262]">Delivery fee</span>
                    <span className="font-bold">
                      {summary.shippingCost > 0
                        ? `৳${summary.shippingCost.toLocaleString()}`
                        : "Free"}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-[#626262]">VAT / Tax</span>
                    <span className="font-bold">
                      ৳{summary.tax.toLocaleString()}
                    </span>
                  </div>
                </div>

                <div className="mb-6 flex items-end justify-between border-t border-[#d6d6d6] pt-6">
                  <span className="text-lg font-bold">Total</span>
                  <span className="text-2xl font-bold">
                    ৳{summary.total.toLocaleString()}
                  </span>
                </div>

                <div className="mb-6">
                  <PaymentMethod
                    value={payment}
                    onValueChange={setPayment}
                    methods={enabledMethods}
                  />
                  {payment !== "cod" && (
                    <div className="mt-3">
                      <label
                        htmlFor="transactionId"
                        className="mb-1 block text-xs font-medium text-[#626262]"
                      >
                        Transaction ID (after you send the payment)
                      </label>
                      <Input
                        id="transactionId"
                        value={transactionId}
                        onChange={(e) => setTransactionId(e.target.value)}
                        placeholder={
                          payment === "bkash"
                            ? "Send to bKash Personal/Merchant, then paste TrxID"
                            : payment === "nagad"
                              ? "Send via Nagad, then paste TrxID"
                              : "Card payment reference"
                        }
                        className="h-9"
                        inputMode="text"
                        autoComplete="off"
                      />
                      <p className="mt-1 text-xs text-[#6a6a6a]">
                        Pay via your payment app to the number shown on your
                        confirmation, then enter the reference. No money is
                        collected on this site.
                      </p>
                    </div>
                  )}
                </div>

                <div className="mb-8 flex gap-2 text-xs text-[#6a6a6a]">
                  <CheckIcon />
                  <p>
                    90 Day Limited Warranty against manufacturer&apos;s defects
                    <Link
                      className="font-bold underline"
                      href="/pages/warranty"
                    >
                      Details
                    </Link>
                  </p>
                </div>

                {error && (
                  <p
                    role="alert"
                    className="mb-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"
                  >
                    {error}
                  </p>
                )}

                <Button
                  className="w-full"
                  onClick={handlePlaceOrder}
                  disabled={submitting}
                >
                  {submitting ? "Placing Order..." : "Place Order"}
                </Button>
              </div>
            </aside>
          </div>
        )}
      </main>
    </div>
  );
}
