"use client";

import {
	RiBankCard2Line,
	RiChat1Line,
	RiCheckboxCircleFill,
	RiFileList2Line,
	RiTimeLine,
} from "@remixicon/react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import Image from "next/image";
import { useState } from "react";
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
import MoneyValues from "@/shared/components/money-values";
import { Badge } from "@/shared/components/ui/badge";
import { Button } from "@/shared/components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "@/shared/components/ui/card";
import { Checkbox } from "@/shared/components/ui/checkbox";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "@/shared/components/ui/dialog";
import { Progress } from "@/shared/components/ui/progress";
import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "@/shared/components/ui/tooltip";
import { resolveLogoSrc } from "@/shared/lib/logo";
import { cn } from "@/shared/utils";
import type { InstallmentGroup } from "./types";

type InstallmentGroupCardProps = {
	group: InstallmentGroup;
	selectedInstallments: Set<string>;
	onToggleGroup: () => void;
	onToggleInstallment: (installmentId: string) => void;
};

export function InstallmentGroupCard({
	group,
	selectedInstallments,
	onToggleGroup,
	onToggleInstallment,
}: InstallmentGroupCardProps) {
	const [isDetailsOpen, setIsDetailsOpen] = useState(false);

	const unpaidInstallments = group.pendingInstallments.filter(
		(i) => !i.isSettled,
	);
	const paidInstallments = group.pendingInstallments.filter((i) => i.isSettled);
	const unpaidCount = unpaidInstallments.length;

	const isFullySelected =
		selectedInstallments.size === unpaidInstallments.length &&
		unpaidInstallments.length > 0;

	const isPartiallySelected = selectedInstallments.size > 0 && !isFullySelected;

	const hasSelection = selectedInstallments.size > 0;

	const progress =
		group.trackedInstallments > 0
			? (group.paidInstallments / group.trackedInstallments) * 100
			: 0;

	const selectedAmount = group.pendingInstallments
		.filter((i) => selectedInstallments.has(i.id) && !i.isSettled)
		.reduce((sum, i) => sum + Number(i.amount), 0);

	const totalAmount = group.pendingInstallments.reduce(
		(sum, i) => sum + i.amount,
		0,
	);

	const pendingAmount = unpaidInstallments.reduce(
		(sum, i) => sum + i.amount,
		0,
	);
	const cardLogoSrc = resolveLogoSrc(group.cartaoLogo);
	const cardName = group.cartaoName ?? "Compra parcelada";
	const hasNote = Boolean(group.note?.trim().length);
	const untrackedLabel =
		group.untrackedInstallments === 1
			? "1 parcela anterior fora do acompanhamento"
			: `${group.untrackedInstallments} parcelas anteriores fora do acompanhamento`;

	return (
		<>
			<Card
				className={cn(
					"overflow-hidden transition-all duration-300",
					isFullySelected && "ring-2 ring-primary/30 border-primary/50",
					isPartiallySelected && "border-primary/30",
				)}
			>
				{/* Header Section */}
				<CardHeader className="pb-0">
					<div className="flex items-start gap-2">
						{/* Checkbox de seleção do grupo */}
						<div className="pt-1">
							<Checkbox
								checked={
									isFullySelected
										? true
										: isPartiallySelected
											? "indeterminate"
											: false
								}
								onCheckedChange={onToggleGroup}
								className="size-4"
								aria-label={`Selecionar todas as parcelas de ${group.name}`}
							/>
						</div>

						{/* Info principal */}
						<div className="flex-1 min-w-0">
							<div className="flex items-center gap-3 flex-wrap">
								<EstablishmentLogo name={group.name} size={40} />
								<div className="flex-1 min-w-0">
									<CardTitle className="flex items-center gap-1 text-base">
										<span className="truncate">{group.name}</span>
										{hasNote ? (
											<Tooltip>
												<TooltipTrigger asChild>
													<span className="inline-flex shrink-0 rounded-full p-1 hover:bg-accent transition-colors duration-300">
														<RiChat1Line
															className="h-4 w-4 text-muted-foreground"
															aria-hidden
														/>
														<span className="sr-only">Ver anotação</span>
													</span>
												</TooltipTrigger>
												<TooltipContent
													side="top"
													align="start"
													className="max-w-xs whitespace-pre-line"
												>
													{group.note}
												</TooltipContent>
											</Tooltip>
										) : null}
									</CardTitle>
									<CardDescription className="flex min-w-0 items-center gap-1 text-xs">
										{cardLogoSrc ? (
											<Image
												src={cardLogoSrc}
												alt={`Logo do cartão ${cardName}`}
												width={18}
												height={18}
												className="size-4.5 shrink-0 rounded-full object-cover"
											/>
										) : (
											<RiBankCard2Line className="size-3.5 shrink-0 text-muted-foreground/70" />
										)}
										<span className="truncate">{cardName}</span>
									</CardDescription>
								</div>
							</div>
						</div>

						{/* Badge de status */}
						<Badge
							variant={progress === 100 ? "default" : "outline"}
							className={cn("shrink-0", progress === 100 && "bg-success")}
						>
							{progress === 100 ? "Quitado" : `${Math.round(progress)}% pago`}
						</Badge>
					</div>
				</CardHeader>

				<CardContent>
					{/* Grid de valores */}
					<div className="grid grid-cols-2 gap-4 p-4 rounded-lg bg-primary/5 mb-4">
						<div className="space-y-1">
							<p className="text-xs text-muted-foreground font-medium">
								Valor acompanhado
							</p>
							<MoneyValues
								amount={totalAmount}
								className="text-lg font-semibold text-foreground"
							/>
						</div>
						<div className="space-y-1 text-right">
							<p className="text-xs text-muted-foreground font-medium">
								Pendente
							</p>
							<MoneyValues
								amount={pendingAmount}
								className={cn(
									"text-lg font-semibold",
									pendingAmount > 0 ? "text-primary" : "text-success",
								)}
							/>
						</div>
					</div>

					{/* Barra de progresso */}
					<div className="space-y-2 mb-4">
						<div className="flex items-center justify-between text-xs">
							<div className="flex items-center gap-1 text-muted-foreground">
								<RiCheckboxCircleFill className="size-3.5 text-success" />
								<span>
									{group.paidInstallments} de {group.trackedInstallments}{" "}
									parcelas acompanhadas pagas
								</span>
							</div>
							{unpaidCount > 0 && (
								<div className="flex items-center gap-1 text-muted-foreground">
									<RiTimeLine className="size-3.5" />
									<span>
										{unpaidCount} {unpaidCount === 1 ? "pendente" : "pendentes"}
									</span>
								</div>
							)}
						</div>
						<Progress
							value={progress}
							className="h-2.5 bg-muted"
							indicatorClassName="bg-success"
						/>
						{group.untrackedInstallments > 0 && (
							<p className="text-xs text-muted-foreground">{untrackedLabel}</p>
						)}
					</div>

					{/* Botão para abrir detalhes */}
					<Button
						type="button"
						variant="secondary"
						size="sm"
						className="relative w-full justify-center gap-1.5"
						onClick={() => setIsDetailsOpen(true)}
					>
						<span className="inline-flex items-center gap-1.5">
							<RiFileList2Line className="size-4" />
							detalhes
						</span>
						{hasSelection && (
							<span className="absolute right-2 rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
								{selectedInstallments.size} sel.
							</span>
						)}
					</Button>
				</CardContent>
			</Card>

			{/* Modal de detalhes */}
			<Dialog open={isDetailsOpen} onOpenChange={setIsDetailsOpen}>
				<DialogContent className="max-w-md max-h-[80vh] flex flex-col">
					<DialogHeader>
						<div className="flex items-center gap-3">
							<EstablishmentLogo name={group.name} size={32} />
							<div className="min-w-0">
								<DialogTitle className="flex items-center gap-1 text-base">
									<span className="truncate">{group.name}</span>
									{hasNote ? (
										<Tooltip>
											<TooltipTrigger asChild>
												<span className="inline-flex shrink-0 rounded-full p-1 hover:bg-accent transition-colors duration-300">
													<RiChat1Line
														className="h-4 w-4 text-muted-foreground"
														aria-hidden
													/>
													<span className="sr-only">Ver anotação</span>
												</span>
											</TooltipTrigger>
											<TooltipContent
												side="top"
												align="start"
												className="max-w-xs whitespace-pre-line"
											>
												{group.note}
											</TooltipContent>
										</Tooltip>
									) : null}
								</DialogTitle>
								<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
									{cardLogoSrc ? (
										<Image
											src={cardLogoSrc}
											alt={`Logo do cartão ${cardName}`}
											width={14}
											height={14}
											className="size-3.5 shrink-0 rounded-full object-cover opacity-75"
										/>
									) : (
										<RiBankCard2Line className="size-3.5 shrink-0 text-muted-foreground/70" />
									)}
									<span className="truncate">{cardName}</span>
								</div>
							</div>
						</div>
						<DialogDescription className="sr-only">
							Detalhes das parcelas do grupo {group.name}
						</DialogDescription>
					</DialogHeader>

					<div className="overflow-y-auto flex-1 space-y-4 pr-1">
						{/* Parcelas pagas */}
						{paidInstallments.length > 0 && (
							<div className="space-y-2">
								<p className="text-xs font-medium text-muted-foreground">
									Parcelas pagas
								</p>
								{paidInstallments.map((installment) => {
									const dueDate = installment.dueDate
										? format(installment.dueDate, "dd MMM yyyy", {
												locale: ptBR,
											})
										: format(installment.purchaseDate, "dd MMM yyyy", {
												locale: ptBR,
											});

									return (
										<div
											key={installment.id}
											className="flex items-center gap-3 p-3 rounded-lg bg-success/5 dark:bg-success/10 border border-success/20 dark:border-success/10"
										>
											<div className="size-8 rounded-full flex items-center justify-center shrink-0">
												<RiCheckboxCircleFill className="size-6 text-success" />
											</div>

											<div className="flex-1 min-w-0">
												<p className="text-sm text-success">
													Parcela {installment.currentInstallment}/
													{group.totalInstallments}
												</p>
												<p className="text-xs text-success/80">
													Vencimento: {dueDate}
												</p>
											</div>

											<MoneyValues
												amount={installment.amount}
												className="text-sm font-semibold text-success shrink-0"
											/>
										</div>
									);
								})}
							</div>
						)}

						{/* Parcelas pendentes */}
						{unpaidInstallments.length > 0 && (
							<div className="space-y-2">
								<p className="text-xs font-medium text-muted-foreground">
									Parcelas pendentes
								</p>
								{unpaidInstallments.map((installment) => {
									const isSelected = selectedInstallments.has(installment.id);
									const dueDate = installment.dueDate
										? format(installment.dueDate, "dd MMM yyyy", {
												locale: ptBR,
											})
										: format(installment.purchaseDate, "dd MMM yyyy", {
												locale: ptBR,
											});

									return (
										<label
											key={installment.id}
											className={cn(
												"flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all duration-200",
												isSelected
													? "bg-primary/5 border-primary/30 shadow-sm"
													: "bg-card hover:bg-muted/50 hover:border-border",
											)}
										>
											<Checkbox
												checked={isSelected}
												onCheckedChange={() =>
													onToggleInstallment(installment.id)
												}
												className="size-5"
												aria-label={`Selecionar parcela ${installment.currentInstallment} de ${group.totalInstallments}`}
											/>

											<div className="flex-1 min-w-0">
												<p className="text-sm font-medium">
													Parcela {installment.currentInstallment}/
													{group.totalInstallments}
												</p>
												<p className="text-xs text-muted-foreground flex items-center gap-1">
													<RiTimeLine className="size-3 text-amber-600" />
													Vencimento: {dueDate}
												</p>
											</div>

											<MoneyValues
												amount={installment.amount}
												className={cn(
													"text-sm font-semibold shrink-0",
													isSelected ? "text-primary" : "text-foreground",
												)}
											/>
										</label>
									);
								})}
							</div>
						)}
					</div>

					{/* Footer com resumo da seleção */}
					{hasSelection && (
						<div className="border-t pt-3 mt-1 flex items-center justify-between">
							<span className="text-sm text-muted-foreground">
								{selectedInstallments.size}{" "}
								{selectedInstallments.size === 1
									? "parcela selecionada"
									: "parcelas selecionadas"}
							</span>
							<MoneyValues
								amount={selectedAmount}
								className="text-base font-bold text-primary"
							/>
						</div>
					)}
				</DialogContent>
			</Dialog>
		</>
	);
}
