"use client";

import Box from "@component/Box";
import { Button } from "@component/buttons";
import Container from "@component/Container";
import FlexBox from "@component/FlexBox";
import NextImage from "@component/NextImage";
import { H2, H3, H5, Paragraph, SemiSpan } from "@component/Typography";
import { IconArrowsLeftRight, IconTrash } from "@tabler/icons-react";
import { currency } from "@utils/utils";
import { useCompare } from "@context/compare";
import { useCart } from "context/helpers/cart";
import { useAuth } from "context/helpers/auth";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

export default function ComparePage() {
	const { compareItems, removeFromCompare } = useCompare() as any;
	const { addToCart } = useCart();
	const { user } = useAuth();
	const router = useRouter();
	const [loadingId, setLoadingId] = useState<string | null>(null);

	const handleAddToCart = async (item: any) => {
		if (!user) {
			router.push("/login");
			return;
		}
		const id = String(item.entityId || item.productId || item.id);
		setLoadingId(id);
		try {
			await addToCart({ ...item, id, entityId: id, productId: id }, 1);
		} finally {
			setLoadingId(null);
		}
	};

	if (!compareItems || compareItems.length === 0) {
		return (
			<Container my="2rem">
				<FlexBox flexDirection="column" alignItems="center" justifyContent="center" minHeight="400px">
					<IconArrowsLeftRight size={64} color="#ccc" style={{ marginBottom: "1rem" }} />
					<H2 mb="0.5rem">No items to compare</H2>
					<Paragraph color="text.muted" mb="1.5rem">
						Add products to compare by clicking the compare icon on product cards.
					</Paragraph>
					<Link href="/">
						<Button color="primary" variant="contained">
							Continue Shopping
						</Button>
					</Link>
				</FlexBox>
			</Container>
		);
	}

	const attrs = Array.from(
		new Set(compareItems.flatMap((item: any) => Object.keys(item?.attributes || {})))
	) as string[];

	return (
		<Container my="2rem">
			<H2 mb="1.5rem" display="flex" alignItems="center" style={{ gap: 8 }}>
				<IconArrowsLeftRight size={28} />
				Compare Products
			</H2>

			<Box style={{ overflowX: "auto" }}>
				<table style={{ width: "100%", borderCollapse: "collapse", minWidth: 600 }}>
					<thead>
						<tr>
							<th style={{ padding: "12px 16px", textAlign: "left", borderBottom: "2px solid #eee", width: 150 }}>
								<SemiSpan>Product</SemiSpan>
							</th>
							{compareItems.map((item: any) => {
								const id = String(item.entityId || item.productId || item.id);
								const img = item.thumbNail || item.imageGallery?.[0]?.smallImage || item.MainImageUrl || "";
								const name = item.name || item.productName || item.title || "";
								return (
									<th key={id} style={{ padding: "12px 16px", textAlign: "center", borderBottom: "2px solid #eee" }}>
										<FlexBox flexDirection="column" alignItems="center" style={{ gap: 8 }}>
											{img && (
												<Box style={{ width: 100, height: 100, position: "relative" }}>
													<NextImage src={img} alt={name} width={100} height={100} style={{ objectFit: "contain" }} />
												</Box>
											)}
											<Link href={`/product/${item.slug || id}`}>
												<H5 fontSize="13px" color="primary.main" style={{ cursor: "pointer" }}>
													{name}
												</H5>
											</Link>
											<Button
												size="none"
												p="2px 6px"
												color="error"
												variant="text"
												onClick={() => (removeFromCompare as (id: string) => void)(id)}
												style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12 }}
											>
												<IconTrash size={14} />
												Remove
											</Button>
										</FlexBox>
									</th>
								);
							})}
						</tr>
					</thead>
					<tbody>
						<tr style={{ background: "#fafafa" }}>
							<td style={{ padding: "12px 16px", borderBottom: "1px solid #eee" }}>
								<SemiSpan fontWeight="600">Price</SemiSpan>
							</td>
							{compareItems.map((item: any) => {
								const id = String(item.entityId || item.productId || item.id);
								const price = item.finalPrice || item.price || 0;
								const formatted = item.formattedFinalPrice || item.formattedPrice || null;
								return (
									<td key={id} style={{ padding: "12px 16px", textAlign: "center", borderBottom: "1px solid #eee" }}>
										<H3 color="primary.main" fontSize="16px">
											{formatted ? (
												<span dangerouslySetInnerHTML={{ __html: formatted }} />
											) : (
												currency(price)
											)}
										</H3>
									</td>
								);
							})}
						</tr>

						<tr>
							<td style={{ padding: "12px 16px", borderBottom: "1px solid #eee" }}>
								<SemiSpan fontWeight="600">Availability</SemiSpan>
							</td>
							{compareItems.map((item: any) => {
								const id = String(item.entityId || item.productId || item.id);
								const available = item.isAvailable !== false;
								return (
									<td key={id} style={{ padding: "12px 16px", textAlign: "center", borderBottom: "1px solid #eee" }}>
										<SemiSpan color={available ? "success.main" : "error.main"}>
											{available ? "In Stock" : "Out of Stock"}
										</SemiSpan>
									</td>
								);
							})}
						</tr>

						{attrs.map((attr) => (
							<tr key={attr} style={{ background: "#fafafa" }}>
								<td style={{ padding: "12px 16px", borderBottom: "1px solid #eee" }}>
									<SemiSpan fontWeight="600" style={{ textTransform: "capitalize" }}>{attr}</SemiSpan>
								</td>
								{compareItems.map((item: any) => {
									const id = String(item.entityId || item.productId || item.id);
									const val = item.attributes?.[attr] ?? "—";
									return (
										<td key={id} style={{ padding: "12px 16px", textAlign: "center", borderBottom: "1px solid #eee" }}>
											<SemiSpan>{String(val)}</SemiSpan>
										</td>
									);
								})}
							</tr>
						))}

						<tr>
							<td style={{ padding: "12px 16px" }}>
								<SemiSpan fontWeight="600">Action</SemiSpan>
							</td>
							{compareItems.map((item: any) => {
								const id = String(item.entityId || item.productId || item.id);
								return (
									<td key={id} style={{ padding: "12px 16px", textAlign: "center" }}>
										<Button
											color="primary"
											variant="contained"
											size="small"
											onClick={() => handleAddToCart(item)}
											disabled={loadingId === id}
										>
											{loadingId === id ? "Adding..." : "Add to Cart"}
										</Button>
									</td>
								);
							})}
						</tr>
					</tbody>
				</table>
			</Box>
		</Container>
	);
}
