"use client";

import Box from "@component/Box";
import { Button } from "@component/buttons";
import { Card1 } from "@component/Card1";
import Divider from "@component/Divider";
import FlexBox from "@component/FlexBox";
import Grid from "@component/grid/Grid";
import Icon from "@component/icon/Icon";
import Image from "@component/Image";
import Typography from "@component/Typography";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

type LastOrderItem = {
	id?: string | number;
	productId?: string | number;
	name?: string;
	qty?: number;
	quantity?: number;
	formattedPrice?: string;
	image?: string;
};

type LastOrder = {
	orderNumber?: string;
	orderDate?: string;
	email?: string;
	total?: string;
	orderCurrencyCode?: string;
	items?: LastOrderItem[];
	shippingAddress?: Record<string, unknown>;
	estimatedDelivery?: string;
};

function safeParseJson<T>(value: string | null): T | null {
	if (!value) return null;
	try {
		return JSON.parse(value) as T;
	} catch {
		return null;
	}
}

function getString(v: unknown): string {
	return typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
}

export default function OrderSuccessPage() {
	const { t } = useTranslation();
	const searchParams = useSearchParams();
	const orderId = searchParams.get("orderId") || "";

	const [lastOrder, setLastOrder] = useState<LastOrder | null>(null);

	useEffect(() => {
		try {
			const raw = localStorage.getItem("lastOrder");
			setLastOrder(safeParseJson<LastOrder>(raw));
		} catch {
			setLastOrder(null);
		}
	}, []);

	const items = useMemo(() => (Array.isArray(lastOrder?.items) ? lastOrder!.items! : []), [lastOrder]);
	const orderNumber = lastOrder?.orderNumber || orderId || "";

	const shipping = (lastOrder?.shippingAddress || {}) as any;
	const shippingName = [getString(shipping?.first_name || shipping?.firstName), getString(shipping?.last_name || shipping?.lastName)]
		.filter(Boolean)
		.join(" ")
		.trim();
	const shippingLines = [
		getString(shipping?.address1 || shipping?.street || ""),
		[getString(shipping?.city), getString(shipping?.state), getString(shipping?.postcode)].filter(Boolean).join(", "),
		getString(shipping?.country || ""),
	].filter(Boolean);
	const shippingPhone = getString(shipping?.phone || shipping?.telephone || "");
	const shippingEmail = getString(shipping?.email || "");

	return (
		<Box>
			<Card1 mb="1.5rem" borderRadius={12}>
				<FlexBox alignItems="center" gap="12px" mb="0.75rem">
					<FlexBox
						alignItems="center"
						justifyContent="center"
						width="44px"
						height="44px"
						borderRadius="999px"
						bg="primary.light"
						color="primary.main"
					>
						<Icon size="22px">check</Icon>
					</FlexBox>
					<Box>
						<Typography fontWeight="800" fontSize="22px" lineHeight="1.2">
							{t("orderSuccess.title", "Thank you! Your order has been placed.")}
						</Typography>
						<Typography color="text.hint" mt="0.25rem">
							{t("orderSuccess.orderNumber", "Order number")}: <b>{orderNumber || "-"}</b>
						</Typography>
					</Box>
				</FlexBox>

				<Divider mb="1rem" />

				<Grid container spacing={4}>
					<Grid item md={6} xs={12}>
						<Typography color="text.hint">{t("orderSuccess.total", "Total")}</Typography>
						{lastOrder?.total ? (
							<Typography fontWeight="800" fontSize="22px" mt="0.25rem">
								<span dangerouslySetInnerHTML={{ __html: String(lastOrder.total) }} />
							</Typography>
						) : (
							<Typography fontWeight="800" fontSize="22px" mt="0.25rem">
								-
							</Typography>
						)}
					</Grid>

					<Grid item md={6} xs={12}>
						{(shippingName || shippingLines.length || shippingPhone || shippingEmail) && (
							<Box>
								<Typography color="text.hint">{t("checkout.deliveryAddress", "Delivery address")}</Typography>
								<Typography fontWeight="700" mt="0.25rem">
									{shippingName || "-"}
								</Typography>
								{shippingLines.map((l) => (
									<Typography key={l} color="text.hint" lineHeight="1.6">
										{l}
									</Typography>
								))}
								{shippingPhone ? (
									<Typography color="text.hint" lineHeight="1.6">
										T: {shippingPhone}
									</Typography>
								) : null}
								{shippingEmail ? (
									<Typography color="text.hint" lineHeight="1.6">
										{shippingEmail}
									</Typography>
								) : null}
							</Box>
						)}
					</Grid>
				</Grid>
			</Card1>

			{items.length > 0 ? (
				<Card1 mb="1.5rem" borderRadius={12}>
					<FlexBox justifyContent="space-between" alignItems="center" mb="1rem" flexWrap="wrap" gap="8px">
						<Typography fontWeight="800">{t("orderSuccess.items", "Items")}</Typography>
						<Typography color="text.hint">
							{items.length} {t("checkout.items", "Items")}
						</Typography>
					</FlexBox>

					<Grid container spacing={4}>
						{items.map((it, idx) => {
							const key = String(it.id ?? it.productId ?? idx);
							const qty = it.qty ?? it.quantity ?? 1;
							return (
								<Grid item xs={12} key={key}>
									<FlexBox
										alignItems="center"
										justifyContent="space-between"
										gap="12px"
										flexWrap="wrap"
										p="0.75rem"
										borderRadius={10}
										bg="gray.100"
									>
										<FlexBox alignItems="center" gap="12px" flex="1 1 320px">
											<Image
												src={it.image || "/assets/images/products/placeholder.png"}
												alt={it.name || "product"}
												width="56px"
												height="56px"
												borderRadius="10px"
												style={{ objectFit: "cover" }}
											/>
											<Box>
												<Typography fontWeight="700" lineHeight="1.35">
													{it.name || "-"}
												</Typography>
												<Typography color="text.hint" lineHeight="1.6">
													{t("orderSuccess.qty", "Qty")}: {qty}
												</Typography>
											</Box>
										</FlexBox>

										{it.formattedPrice ? (
											<Typography fontWeight="800" textAlign="end" dangerouslySetInnerHTML={{ __html: String(it.formattedPrice) }} />
										) : (
											<Typography fontWeight="800">-</Typography>
										)}
									</FlexBox>
								</Grid>
							);
						})}
					</Grid>
				</Card1>
			) : null}

			<Grid container spacing={4}>
				<Grid item sm={6} xs={12}>
					<Link href="/">
						<Button variant="contained" color="primary" fullWidth>
							{t("cart.continueShopping")}
						</Button>
					</Link>
				</Grid>
				<Grid item sm={6} xs={12}>
					<Link href="/orders">
						<Button variant="outlined" color="primary" fullWidth>
							{t("orderSuccess.viewOrders", "View orders")}
						</Button>
					</Link>
				</Grid>
			</Grid>
		</Box>
	);
}

