import { Head, router } from '@inertiajs/react';
import { Button } from '@ui/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@ui/components/ui/card';
import { Input } from '@ui/components/ui/input';
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, Search } from 'lucide-react';
import { useMemo, useState } from 'react';
import { FinanceAppLayout } from '@/layouts/finance-app-layout';

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

interface ReportRow {
	account_number: string;
	description: string;
	allocated_amount: number;
	used_amount: number;
	remaining_amount: number;
	realization_ratio: number;
	variance_ratio: number;
}

interface Props {
	reportData: {
		rows: ReportRow[];
		summary: {
			total_allocated: number;
			total_used: number;
			total_remaining: number;
		};
	};
	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 UserCostControl({ reportData, filters }: Props) {
	const [search, setSearch] = useState('');
	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 rows = useMemo(() => {
		if (!search.trim()) {
			return reportData.rows;
		}

		const keyword = search.toLowerCase();

		return reportData.rows.filter(
			(row) =>
				row.account_number.toLowerCase().includes(keyword) ||
				row.description.toLowerCase().includes(keyword),
		);
	}, [reportData.rows, search]);

	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 exportStandard = () => {
		window.location.href = `/department/finance/reporting/fund-request-service/export?year=${year}&month=${month}`;
	};

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

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

			<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
						</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={exportStandard}>
							<Download className='mr-2 h-4 w-4' />
							Export Excel
						</Button>
					</div>
				</div>

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

				<Card className='overflow-hidden rounded-xl border'>
					<CardHeader className='flex flex-col gap-4 border-b p-5 md:flex-row md:items-center md:justify-between'>
						<CardTitle className='text-xl font-semibold text-foreground'>
							Rincian Anggaran & Realisasi
						</CardTitle>

						<div className='relative w-full md:w-[380px]'>
							<Search className='absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground' />
							<Input
								value={search}
								onChange={(event) => setSearch(event.target.value)}
								className='h-11 rounded-2xl pl-10 text-sm'
								placeholder='Cari No. Akun atau Keterangan...'
							/>
						</div>
					</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>
								{rows.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>
								) : (
									rows.map((row) => (
										<TableRow key={`${row.account_number}-${row.description}`}>
											<TableCell className='font-mono font-semibold'>{row.account_number}</TableCell>
											<TableCell className='max-w-[460px] truncate'>{row.description}</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.allocated_amount)}</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.used_amount)}</TableCell>
											<TableCell className='text-right font-mono'>{formatCurrency(row.remaining_amount)}</TableCell>
											<TableCell className='text-right font-mono'>
												{row.realization_ratio.toFixed(2)}%
											</TableCell>
											<TableCell className='text-right font-mono'>
												{row.variance_ratio.toFixed(2)}%
											</TableCell>
										</TableRow>
									))
								)}

								{rows.length > 0 ? (
									<TableRow className='bg-slate-50 font-semibold'>
										<TableCell colSpan={2} className='text-right'>TOTAL</TableCell>
										<TableCell className='text-right font-mono'>
											{formatCurrency(reportData.summary.total_allocated)}
										</TableCell>
										<TableCell className='text-right font-mono'>
											{formatCurrency(reportData.summary.total_used)}
										</TableCell>
										<TableCell className='text-right font-mono'>
											{formatCurrency(reportData.summary.total_remaining)}
										</TableCell>
										<TableCell className='text-right font-mono'>
											{reportData.summary.total_allocated > 0
												? ((reportData.summary.total_used / reportData.summary.total_allocated) * 100).toFixed(2)
												: '0.00'}%
										</TableCell>
										<TableCell className='text-right font-mono'>
											{reportData.summary.total_allocated > 0
												? ((reportData.summary.total_remaining / reportData.summary.total_allocated) * 100).toFixed(2)
												: '0.00'}%
										</TableCell>
									</TableRow>
								) : null}
							</TableBody>
						</Table>
					</CardContent>
				</Card>
			</div>
		</FinanceAppLayout>
	);
}
