import { Head, router } from '@inertiajs/react';
import { Button } from '@ui/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@ui/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ui/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@ui/components/ui/table';
import { Download } from 'lucide-react';
import { useMemo, useState } from 'react';
import { FinanceAppLayout } from '@/layouts/finance-app-layout';

interface Department {
	id: number;
	name: string;
}

interface ConsolidatedNode {
	id: number;
	code: string;
	name: string;
	budget: number;
	realization: number;
	sisa: number;
	ratio_actual: number;
	ratio_sisa: number;
	children: ConsolidatedNode[];
}

interface Props {
	reportData: ConsolidatedNode[];
	filters: {
		year: number;
		month: number;
		departments: Department[];
	};
}

const monthOptions = [
	{ value: 1, label: 'January' },
	{ value: 2, label: 'February' },
	{ value: 3, label: 'March' },
	{ value: 4, label: 'April' },
	{ value: 5, label: 'May' },
	{ value: 6, label: 'June' },
	{ value: 7, label: 'July' },
	{ value: 8, label: 'August' },
	{ value: 9, label: 'September' },
	{ value: 10, label: 'October' },
	{ value: 11, label: 'November' },
	{ value: 12, label: 'December' },
];

const yearOptions = [2024, 2025, 2026, 2027, 2028];

export default function UserCostControlConsolidated({ reportData, filters }: Props) {
	const [year, setYear] = useState(filters.year.toString());
	const [month, setMonth] = useState(filters.month.toString());

	const departmentLabel =
		filters.departments.length > 0
			? filters.departments.map((dep) => dep.name).join(', ')
			: 'All Departments';

	const goToStandard = () => {
		router.get('/department/finance/reporting/fund-request-service', {
			year,
			month,
		});
	};

	const goToConsolidated = () => {
		router.get('/department/finance/reporting/fund-request-service/consolidated', {
			year,
			month,
		});
	};

	const exportConsolidated = () => {
		window.location.href = `/department/finance/reporting/fund-request-service/consolidated/export?year=${year}&month=${month}`;
	};

	const flattenedRows = useMemo(() => {
		const output: Array<ConsolidatedNode & { depth: number }> = [];

		const walk = (rows: ConsolidatedNode[], depth: number): void => {
			rows.forEach((row) => {
				output.push({ ...row, depth });

				if (row.children && row.children.length > 0) {
					walk(row.children, depth + 1);
				}
			});
		};

		walk(reportData, 0);

		return output;
	}, [reportData]);

	const totals = useMemo(() => {
		return flattenedRows.reduce(
			(acc, row) => {
				if (row.depth === 0) {
					acc.budget += row.budget;
					acc.realization += row.realization;
					acc.sisa += row.sisa;
				}

				return acc;
			},
			{ budget: 0, realization: 0, sisa: 0 },
		);
	}, [flattenedRows]);

	const formatCurrency = (value: number): string => {
		return new Intl.NumberFormat('id-ID').format(value || 0);
	};

	return (
		<FinanceAppLayout>
			<Head title='Laporan Varians Antar Divisi - Consolidated' />

			<div className='flex h-full flex-1 flex-col gap-4 p-4'>
				<div className='flex items-center justify-between'>
					<div>
						<h1 className='text-2xl font-bold tracking-tight text-foreground'>
							Laporan Varians Antar Divisi — Konsolidasi
						</h1>
						<p className='text-muted-foreground'>
							Tahun {year} — {departmentLabel}
						</p>
					</div>

					<div className='flex items-center gap-3'>
						<div>
							<p className='mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground'>
								Bulan
							</p>
							<Select value={month} onValueChange={setMonth}>
								<SelectTrigger className='h-9 w-[180px]'>
									<SelectValue placeholder='Pilih Bulan' />
								</SelectTrigger>
								<SelectContent>
									{monthOptions.map((option) => (
										<SelectItem key={option.value} value={option.value.toString()}>
											{option.label}
										</SelectItem>
									))}
								</SelectContent>
							</Select>
						</div>

						<div>
							<p className='mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground'>
								Tahun
							</p>
							<Select value={year} onValueChange={setYear}>
								<SelectTrigger className='h-9 w-[120px]'>
									<SelectValue placeholder='Pilih Tahun' />
								</SelectTrigger>
								<SelectContent>
									{yearOptions.map((option) => (
										<SelectItem key={option} value={option.toString()}>
											{option}
										</SelectItem>
									))}
								</SelectContent>
							</Select>
						</div>

						<Button onClick={exportConsolidated}>
							<Download className='mr-2 h-4 w-4' />
							Export Excel
						</Button>
					</div>
				</div>

				<div className='inline-flex rounded-lg bg-muted p-1'>
					<Button
						variant='ghost'
						className='h-9 rounded-md px-6 hover:bg-muted-foreground/10'
						onClick={goToStandard}
					>
						Standard View
					</Button>
					<Button className='h-9 rounded-md px-6' onClick={goToConsolidated}>
						Consolidated View
					</Button>
				</div>

				<Card className='overflow-hidden rounded-xl border'>
					<CardHeader className='border-b p-5'>
						<CardTitle className='text-xl font-semibold text-foreground'>
							Rincian Konsolidasi Anggaran
						</CardTitle>
					</CardHeader>

					<CardContent className='p-0'>
						<Table>
							<TableHeader>
								<TableRow className='bg-slate-800 hover:bg-slate-800'>
									<TableHead className='h-16 text-lg font-semibold text-white'>No. Account</TableHead>
									<TableHead className='h-16 text-lg font-semibold text-white'>Keterangan</TableHead>
									<TableHead className='h-16 text-right text-lg font-semibold text-white'>Anggaran Dana</TableHead>
									<TableHead className='h-16 text-right text-lg font-semibold text-white'>Realisasi Dana</TableHead>
									<TableHead className='h-16 text-right text-lg font-semibold text-white'>Sisa Dana</TableHead>
									<TableHead className='h-16 text-right text-lg font-semibold text-white'>Rasio Actual</TableHead>
									<TableHead className='h-16 text-right text-lg font-semibold text-white'>Varians</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{flattenedRows.length === 0 ? (
									<TableRow>
										<TableCell colSpan={7} className='h-28 text-center text-xl text-slate-400'>
											Tidak ada data anggaran untuk periode ini.
										</TableCell>
									</TableRow>
								) : (
									flattenedRows.map((row) => (
										<TableRow key={`${row.id}-${row.depth}`} className={row.depth === 0 ? 'bg-slate-50/70' : ''}>
											<TableCell className='font-mono font-semibold'>{row.code}</TableCell>
											<TableCell className='max-w-[460px] truncate' style={{ paddingLeft: `${row.depth * 24 + 16}px` }}>
												{row.name}
											</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.budget)}</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.realization)}</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.sisa)}</TableCell>
											<TableCell className='text-right font-mono'>{row.ratio_actual.toFixed(2)}%</TableCell>
											<TableCell className='text-right font-mono'>{row.ratio_sisa.toFixed(2)}%</TableCell>
										</TableRow>
									))
								)}

								{flattenedRows.length > 0 ? (
									<TableRow className='bg-slate-100 font-semibold'>
										<TableCell colSpan={2} className='text-right'>TOTAL</TableCell>
										<TableCell className='text-right font-mono'>{formatCurrency(totals.budget)}</TableCell>
										<TableCell className='text-right font-mono'>{formatCurrency(totals.realization)}</TableCell>
										<TableCell className='text-right font-mono'>{formatCurrency(totals.sisa)}</TableCell>
										<TableCell className='text-right font-mono'>
											{totals.budget > 0 ? ((totals.realization / totals.budget) * 100).toFixed(2) : '0.00'}%
										</TableCell>
										<TableCell className='text-right font-mono'>
											{totals.budget > 0 ? ((totals.sisa / totals.budget) * 100).toFixed(2) : '0.00'}%
										</TableCell>
									</TableRow>
								) : null}
							</TableBody>
						</Table>
					</CardContent>
				</Card>
			</div>
		</FinanceAppLayout>
	);
}
