import { Head } from '@inertiajs/react';
import { Download, Printer } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import {
    Table,
    TableBody,
    TableCell,
    TableFooter,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import AppLayout from '@/layouts/app-layout';
import { formatIDR } from '@/lib/formatters';
import { useFilterParams } from '@/lib/hooks/useFilterParams';
import accountingRoutes from '@/routes/accounting';
import type { BreadcrumbItem } from '@/types';

interface IncomeItem {
    code: string;
    name: string;
    balance: number;
}

interface PageProps {
    revenues: IncomeItem[];
    expenses: IncomeItem[];
    total_revenue: number;
    total_expenses: number;
    net_income: number;
    date_from: string;
    date_to: string;
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Akuntansi',
        href: accountingRoutes.accounts.index().url,
    },
    {
        title: 'Laporan Keuangan',
        href: '#',
    },
    {
        title: 'Laba Rugi (Income Statement)',
        href: accountingRoutes.reports.incomeStatement().url,
    },
];

export default function IncomeStatement({
    revenues,
    expenses,
    total_revenue,
    total_expenses,
    net_income,
    date_from,
    date_to,
}: PageProps) {
    const { updateFilter } = useFilterParams({
        baseUrl: accountingRoutes.reports.incomeStatement().url,
    });

    const handleDateChange = (
        field: 'date_from' | 'date_to',
        value: string,
    ) => {
        updateFilter(field, value);
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Laba Rugi (Income Statement)" />

            <div className="mx-auto flex h-full w-full max-w-4xl flex-col gap-4 p-4">
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div className="flex flex-col gap-1">
                        <h1 className="text-2xl font-black">
                            Laba Rugi (Income Statement)
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            Kinerja pendapatan dan beban dalam periode tertentu.
                        </p>
                    </div>
                    <div className="flex gap-2">
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button variant="outline" size="sm">
                                    <Download className="mr-2 h-4 w-4" />
                                    Export
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                <DropdownMenuItem asChild>
                                    <a
                                        href={
                                            accountingRoutes.reports.incomeStatement.export(
                                                {
                                                    query: {
                                                        date_from:
                                                            date_from.split(
                                                                'T',
                                                            )[0],
                                                        date_to:
                                                            date_to.split(
                                                                'T',
                                                            )[0],
                                                        format: 'pdf',
                                                    },
                                                },
                                            ).url
                                        }
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="w-full cursor-pointer"
                                    >
                                        Export PDF
                                    </a>
                                </DropdownMenuItem>
                                <DropdownMenuItem asChild>
                                    <a
                                        href={
                                            accountingRoutes.reports.incomeStatement.export(
                                                {
                                                    query: {
                                                        date_from:
                                                            date_from.split(
                                                                'T',
                                                            )[0],
                                                        date_to:
                                                            date_to.split(
                                                                'T',
                                                            )[0],
                                                        format: 'csv',
                                                    },
                                                },
                                            ).url
                                        }
                                        className="w-full cursor-pointer"
                                    >
                                        Export CSV
                                    </a>
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => window.print()}
                        >
                            <Printer className="mr-2 h-4 w-4" />
                            Cetak
                        </Button>
                    </div>
                </div>

                <Card className="mb-2">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
                        <CardTitle className="text-sm font-medium">
                            Filter Periode
                        </CardTitle>
                        <div className="flex items-center gap-2">
                            <Input
                                type="date"
                                className="w-40"
                                value={date_from.split('T')[0]}
                                onChange={(e) =>
                                    handleDateChange(
                                        'date_from',
                                        e.target.value,
                                    )
                                }
                            />
                            <span className="text-muted-foreground">s/d</span>
                            <Input
                                type="date"
                                className="w-40"
                                value={date_to.split('T')[0]}
                                onChange={(e) =>
                                    handleDateChange('date_to', e.target.value)
                                }
                            />
                        </div>
                    </CardHeader>
                </Card>

                <div className="flex flex-col gap-6">
                    {/* REVENUES SECTION */}
                    <Card>
                        <CardHeader className="bg-green-50/50">
                            <CardTitle className="text-lg text-green-700">
                                PENDAPATAN (REVENUES)
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="p-0">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Akun</TableHead>
                                        <TableHead className="text-right">
                                            Jumlah
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {revenues.length > 0 ? (
                                        revenues.map((item: IncomeItem) => (
                                            <TableRow key={item.code}>
                                                <TableCell className="py-2">
                                                    <div className="flex flex-col">
                                                        <span className="font-medium">
                                                            {item.name}
                                                        </span>
                                                        <span className="font-mono text-xs text-muted-foreground">
                                                            {item.code}
                                                        </span>
                                                    </div>
                                                </TableCell>
                                                <TableCell className="py-2 text-right font-medium">
                                                    {formatIDR(item.balance)}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell
                                                colSpan={2}
                                                className="h-20 text-center text-muted-foreground italic"
                                            >
                                                Tidak ada data pendapatan
                                                ditemukan.
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                                <TableFooter>
                                    <TableRow className="bg-green-50">
                                        <TableCell className="text-base font-bold text-green-700 uppercase">
                                            Total Pendapatan
                                        </TableCell>
                                        <TableCell className="text-right text-base font-bold text-green-700">
                                            {formatIDR(total_revenue)}
                                        </TableCell>
                                    </TableRow>
                                </TableFooter>
                            </Table>
                        </CardContent>
                    </Card>

                    {/* EXPENSES SECTION */}
                    <Card>
                        <CardHeader className="bg-red-50/50">
                            <CardTitle className="text-lg text-red-700">
                                BEBAN (EXPENSES)
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="p-0">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Akun</TableHead>
                                        <TableHead className="text-right">
                                            Jumlah
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {expenses.length > 0 ? (
                                        expenses.map((item: IncomeItem) => (
                                            <TableRow key={item.code}>
                                                <TableCell className="py-2">
                                                    <div className="flex flex-col">
                                                        <span className="font-medium">
                                                            {item.name}
                                                        </span>
                                                        <span className="font-mono text-xs text-muted-foreground">
                                                            {item.code}
                                                        </span>
                                                    </div>
                                                </TableCell>
                                                <TableCell className="py-2 text-right font-medium">
                                                    {formatIDR(item.balance)}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell
                                                colSpan={2}
                                                className="h-20 text-center text-muted-foreground italic"
                                            >
                                                Tidak ada data beban ditemukan.
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                                <TableFooter>
                                    <TableRow className="bg-red-50">
                                        <TableCell className="text-base font-bold text-red-700 uppercase">
                                            Total Beban
                                        </TableCell>
                                        <TableCell className="text-right text-base font-bold text-red-700">
                                            {formatIDR(total_expenses)}
                                        </TableCell>
                                    </TableRow>
                                </TableFooter>
                            </Table>
                        </CardContent>
                    </Card>

                    {/* NET INCOME SUMMARY */}
                    <Card
                        className={`border-2 ${net_income >= 0 ? 'border-primary/20' : 'border-red-200'}`}
                    >
                        <CardContent
                            className={`flex items-center justify-between rounded-lg p-6 ${net_income >= 0 ? 'bg-primary/5' : 'bg-red-50/50'}`}
                        >
                            <div className="flex flex-col">
                                <span className="text-lg font-black uppercase">
                                    Laba / (Rugi) Bersih
                                </span>
                                <span className="text-xs font-bold tracking-widest text-muted-foreground uppercase italic">
                                    Net Income
                                </span>
                            </div>
                            <span
                                className={`text-2xl font-black ${net_income >= 0 ? 'text-primary' : 'text-red-700'}`}
                            >
                                {formatIDR(net_income)}
                            </span>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AppLayout>
    );
}
