import { Head, Link, usePage } from '@inertiajs/react';
import {
    AlertCircle,
    Award,
    Banknote,
    BarChart3,
    Building2,
    CalendarCheck2,
    GraduationCap,
    HeartHandshake,
    Plus,
    Receipt,
    TrendingDown,
    Users,
    Wallet,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useI18n } from '@/hooks/use-i18n';
import { dashboard } from '@/routes';
import { index as chandaIndex } from '@/routes/chanda';
import { index as expensesIndex } from '@/routes/expenses';
import { index as invoicesIndex, show as showInvoice } from '@/routes/invoices';
import { create as createStudent } from '@/routes/students';
import type { Auth, TenantSharedProps } from '@/types';

type DashboardStats = {
    activeStudents: number;
    departmentsCount: number;
    monthlyCollection: number;
    monthlyFeeCollection: number;
    monthlyChandaCollection: number;
    monthlyExpense: number;
    todayCollection: number;
    totalDue: number;
    overdueInvoicesCount: number;
    feeCategoriesCount: number;
    donationFundsCount: number;
    activeDonorsCount: number;
    todayPresentCount: number;
    todayMarkedCount: number;
};

type LocalizedName = {
    id: number;
    name_bn: string;
    name_en: string | null;
};

type RecentInvoice = {
    id: number;
    invoice_number: string;
    billing_year: number;
    billing_month: number;
    total_amount: string | number;
    due_amount: string | number;
    status: string;
    student?: {
        id: number;
        student_code: string;
        name_bn: string;
        name_en: string | null;
    } | null;
};

type DonationFundSummary = LocalizedName & {
    code: string;
    is_restricted: boolean;
    balance: number;
};

type DepartmentBreakdownItem = LocalizedName & {
    active_students_count: number;
};

type MonthlyTrendItem = {
    label: string;
    income: number;
    expense: number;
};

type LatestExam = LocalizedName & {
    status: string;
};

type DashboardProps = {
    stats: DashboardStats;
    currentSession: LocalizedName | null;
    latestExam: LatestExam | null;
    recentInvoices: RecentInvoice[];
    donationFunds: DonationFundSummary[];
    departmentBreakdown: DepartmentBreakdownItem[];
    monthlyTrend: MonthlyTrendItem[];
};

const statusPillClasses: Record<string, string> = {
    paid: 'bg-[#22C55E]/15 text-[#118D57] dark:text-[#77ED8B]',
    partial: 'bg-[#FFAB00]/15 text-[#B76E00] dark:text-[#FFD666]',
    unpaid: 'bg-[#FF5630]/15 text-[#B71D18] dark:text-[#FFAC82]',
    overdue: 'bg-[#FF5630]/20 text-[#B71D18] dark:text-[#FFAC82]',
};

export default function Dashboard({
    stats,
    currentSession,
    latestExam,
    recentInvoices,
    donationFunds,
    departmentBreakdown,
    monthlyTrend,
}: DashboardProps) {
    const { props } = usePage<{ auth: Auth; tenant?: TenantSharedProps }>();
    const { locale, t, localized } = useI18n();
    const institution = props.tenant?.activeInstitution ?? null;

    const formatBdt = (value: number | string): string => {
        const numeric = Number(value) || 0;
        return `৳${numeric.toLocaleString(locale === 'bn' ? 'bn-BD' : 'en-US')}`;
    };

    const formatCount = (value: number): string => {
        return value.toLocaleString(locale === 'bn' ? 'bn-BD' : 'en-US');
    };

    const attendanceRate =
        stats.todayMarkedCount > 0 ? Math.round((stats.todayPresentCount / stats.todayMarkedCount) * 100) : 0;
    const netMonthlyBalance = stats.monthlyCollection - stats.monthlyExpense;
    const maxTrendValue = Math.max(1, ...monthlyTrend.flatMap((m) => [m.income, m.expense]));

    const kpiCards = [
        {
            label: locale === 'bn' ? 'সক্রিয় শিক্ষার্থী' : 'Active Students',
            value: formatCount(stats.activeStudents),
            subtitle:
                locale === 'bn'
                    ? `${formatCount(stats.departmentsCount)}টি বিভাগ সক্রিয়`
                    : `${stats.departmentsCount} active departments`,
            icon: GraduationCap,
            iconBg: 'bg-[#00A76F]/12 text-[#00A76F]',
        },
        {
            label: locale === 'bn' ? 'চলতি মাসের মোট আয়' : 'Monthly Income',
            value: formatBdt(stats.monthlyCollection),
            subtitle:
                locale === 'bn'
                    ? `ফি ${formatBdt(stats.monthlyFeeCollection)} · চাঁদা ${formatBdt(stats.monthlyChandaCollection)}`
                    : `Fee ${formatBdt(stats.monthlyFeeCollection)} · Chanda ${formatBdt(stats.monthlyChandaCollection)}`,
            icon: Banknote,
            iconBg: 'bg-[#22C55E]/12 text-[#118D57] dark:text-[#77ED8B]',
        },
        {
            label: locale === 'bn' ? 'চলতি মাসের ব্যয়' : 'Monthly Expense',
            value: formatBdt(stats.monthlyExpense),
            subtitle:
                locale === 'bn'
                    ? `নিট স্থিতি: ${formatBdt(netMonthlyBalance)}`
                    : `Net balance: ${formatBdt(netMonthlyBalance)}`,
            icon: TrendingDown,
            iconBg: 'bg-[#FF5630]/12 text-[#B71D18] dark:text-[#FFAC82]',
        },
        {
            label: locale === 'bn' ? 'মোট শিক্ষার্থী বকেয়া' : 'Total Student Due',
            value: formatBdt(stats.totalDue),
            subtitle:
                locale === 'bn'
                    ? `${formatCount(stats.overdueInvoicesCount)}টি বকেয়া ইনভয়েস`
                    : `${stats.overdueInvoicesCount} pending invoices`,
            icon: AlertCircle,
            iconBg: 'bg-[#FFAB00]/15 text-[#B76E00] dark:text-[#FFD666]',
        },
        {
            label: locale === 'bn' ? 'আজকের আদায়' : "Today's Collection",
            value: formatBdt(stats.todayCollection),
            subtitle: locale === 'bn' ? 'আজকের ফি ও চাঁদা জমা' : 'Fees & donations today',
            icon: Wallet,
            iconBg: 'bg-[#00B8D9]/12 text-[#006C9C] dark:text-[#61F3F3]',
        },
        {
            label: locale === 'bn' ? 'আজকের উপস্থিতি' : "Today's Attendance",
            value: stats.todayMarkedCount > 0 ? `${attendanceRate}%` : '—',
            subtitle:
                stats.todayMarkedCount > 0
                    ? locale === 'bn'
                        ? `${formatCount(stats.todayPresentCount)} / ${formatCount(stats.todayMarkedCount)} জন উপস্থিত`
                        : `${stats.todayPresentCount} / ${stats.todayMarkedCount} present`
                    : locale === 'bn'
                      ? 'আজ হাজিরা নেওয়া হয়নি'
                      : 'Not marked today',
            icon: CalendarCheck2,
            iconBg: 'bg-[#00A76F]/12 text-[#00A76F]',
        },
        {
            label: locale === 'bn' ? 'সক্রিয় চাঁদাদাতা' : 'Active Donors',
            value: formatCount(stats.activeDonorsCount),
            subtitle:
                locale === 'bn'
                    ? `${formatCount(stats.donationFundsCount)}টি অনুদান ফান্ড`
                    : `${stats.donationFundsCount} donation funds`,
            icon: Users,
            iconBg: 'bg-[#8E33FF]/12 text-[#8E33FF] dark:text-[#C684FF]',
        },
        {
            label: locale === 'bn' ? 'সর্বশেষ পরীক্ষা' : 'Latest Exam',
            value: latestExam ? localized(latestExam, 'name') : '—',
            subtitle: latestExam
                ? latestExam.status === 'published'
                    ? locale === 'bn'
                        ? 'ফলাফল প্রকাশিত'
                        : 'Results published'
                    : locale === 'bn'
                      ? 'চলমান / খসড়া'
                      : 'Draft / Ongoing'
                : locale === 'bn'
                  ? 'কোনো পরীক্ষা নেই'
                  : 'No exams yet',
            icon: Award,
            iconBg: 'bg-[#FFAB00]/15 text-[#B76E00] dark:text-[#FFD666]',
        },
    ];

    return (
        <>
            <Head title={t('nav.dashboard', 'Dashboard')} />
            <div className="flex w-full flex-1 flex-col gap-6 p-4 md:p-6">
                {/* Welcome Hero Card (Minimal Web v7.3.0 style) */}
                <div className="minimal-card relative overflow-hidden bg-gradient-to-br from-[#00A76F]/12 via-card to-[#007867]/6 p-6">
                    <div className="flex flex-col justify-between gap-4 md:flex-row md:items-center">
                        <div className="space-y-1.5">
                            <p className="text-xs font-bold tracking-wider text-primary uppercase">
                                {currentSession
                                    ? `${t('nav.sessions', 'Session')}: ${localized(currentSession, 'name')}`
                                    : t('app.name', 'Madrasa ERP')}
                            </p>
                            <h1 className="text-xl font-bold tracking-tight text-foreground md:text-2xl">
                                {locale === 'bn'
                                    ? `স্বাগতম, ${props.auth.user.name}`
                                    : `Welcome back, ${props.auth.user.name}`}
                            </h1>
                            <p className="text-sm text-muted-foreground">
                                {institution
                                    ? localized(institution, 'name')
                                    : locale === 'bn'
                                      ? 'কোনো মাদ্রাসা নির্ধারিত নেই'
                                      : 'No madrasa assigned'}
                            </p>
                        </div>

                        <div className="flex flex-wrap items-center gap-2">
                            <Button asChild size="sm">
                                <Link href={createStudent()}>
                                    <Plus className="mr-1 size-4" />
                                    {locale === 'bn' ? 'নতুন ভর্তি' : 'New Admission'}
                                </Link>
                            </Button>
                            <Button asChild size="sm" variant="outline">
                                <Link href={invoicesIndex()}>
                                    <Receipt className="mr-1 size-4" />
                                    {locale === 'bn' ? 'ফি আদায়' : 'Collect Fee'}
                                </Link>
                            </Button>
                            <Button asChild size="sm" variant="outline">
                                <Link href={chandaIndex()}>
                                    <HeartHandshake className="mr-1 size-4" />
                                    {locale === 'bn' ? 'চাঁদা গ্রহণ' : 'Receive Chanda'}
                                </Link>
                            </Button>
                            <Button asChild size="sm" variant="outline">
                                <Link href={expensesIndex()}>
                                    <TrendingDown className="mr-1 size-4" />
                                    {locale === 'bn' ? 'ব্যয় লিপিবদ্ধ' : 'Add Expense'}
                                </Link>
                            </Button>
                        </div>
                    </div>
                </div>

                {/* KPI Cards */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    {kpiCards.map((card) => (
                        <div
                            key={card.label}
                            className="minimal-card flex items-start justify-between p-5"
                        >
                            <div className="space-y-1.5">
                                <p className="text-xs font-semibold text-muted-foreground">
                                    {card.label}
                                </p>
                                <p className="text-2xl font-bold tracking-tight text-foreground tabular-nums">
                                    {card.value}
                                </p>
                                <p className="text-xs text-muted-foreground">{card.subtitle}</p>
                            </div>
                            <div
                                className={`flex size-11 shrink-0 items-center justify-center rounded-xl ${card.iconBg}`}
                            >
                                <card.icon className="size-5" />
                            </div>
                        </div>
                    ))}
                </div>

                {/* 6-Month Income vs Expense & Department Breakdown */}
                <div className="grid gap-6 lg:grid-cols-3">
                    <div className="minimal-card flex flex-col p-5 lg:col-span-2">
                        <div className="mb-4 flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                <BarChart3 className="size-4 text-primary" />
                                <h2 className="text-base font-bold text-foreground">
                                    {locale === 'bn' ? 'গত ৬ মাসের আয় বনাম ব্যয়' : '6-Month Income vs Expense'}
                                </h2>
                            </div>
                            <div className="flex items-center gap-4 text-xs text-muted-foreground">
                                <span className="inline-flex items-center gap-1.5">
                                    <span className="size-2.5 rounded-sm bg-[#00A76F]" />
                                    {locale === 'bn' ? 'মোট আয়' : 'Income'}
                                </span>
                                <span className="inline-flex items-center gap-1.5">
                                    <span className="size-2.5 rounded-sm bg-[#FF5630]" />
                                    {locale === 'bn' ? 'মোট ব্যয়' : 'Expense'}
                                </span>
                            </div>
                        </div>

                        <div className="grid h-44 grid-cols-6 items-end gap-3 pt-4">
                            {monthlyTrend.map((item) => (
                                <div key={item.label} className="flex h-full flex-col items-center justify-end gap-2">
                                    <div className="flex h-32 w-full items-end justify-center gap-1.5">
                                        <div
                                            title={`${locale === 'bn' ? 'আয়' : 'Income'}: ${formatBdt(item.income)}`}
                                            className="w-3.5 rounded-t bg-[#00A76F] transition-all"
                                            style={{ height: `${Math.max(4, Math.round((item.income / maxTrendValue) * 100))}%` }}
                                        />
                                        <div
                                            title={`${locale === 'bn' ? 'ব্যয়' : 'Expense'}: ${formatBdt(item.expense)}`}
                                            className="w-3.5 rounded-t bg-[#FF5630] transition-all"
                                            style={{ height: `${Math.max(4, Math.round((item.expense / maxTrendValue) * 100))}%` }}
                                        />
                                    </div>
                                    <span className="text-[11px] font-medium text-muted-foreground">{item.label}</span>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="minimal-card flex flex-col p-5">
                        <div className="mb-4 flex items-center gap-2">
                            <Building2 className="size-4 text-primary" />
                            <h2 className="text-base font-bold text-foreground">
                                {locale === 'bn' ? 'বিভাগভিত্তিক শিক্ষার্থী' : 'Students by Department'}
                            </h2>
                        </div>
                        <div className="space-y-3.5">
                            {departmentBreakdown.length === 0 ? (
                                <p className="py-6 text-center text-sm text-muted-foreground">
                                    {locale === 'bn' ? 'কোনো বিভাগ নেই' : 'No departments found'}
                                </p>
                            ) : (
                                departmentBreakdown.map((dept) => {
                                    const pct =
                                        stats.activeStudents > 0
                                            ? Math.round((dept.active_students_count / stats.activeStudents) * 100)
                                            : 0;
                                    return (
                                        <div key={dept.id} className="space-y-1.5">
                                            <div className="flex items-center justify-between text-sm">
                                                <span className="font-medium text-foreground">{localized(dept, 'name')}</span>
                                                <span className="font-semibold tabular-nums text-muted-foreground">
                                                    {formatCount(dept.active_students_count)} ({pct}%)
                                                </span>
                                            </div>
                                            <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
                                                <div
                                                    className="h-full rounded-full bg-primary transition-all"
                                                    style={{ width: `${pct}%` }}
                                                />
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </div>
                    </div>
                </div>

                {/* Recent Invoices (2/3) & Donation Funds (1/3) */}
                <div className="grid gap-6 lg:grid-cols-3">
                    <div className="minimal-card flex flex-col lg:col-span-2">
                        <div className="flex items-center justify-between border-b border-border px-5 py-4">
                            <div className="flex items-center gap-2">
                                <Receipt className="size-4 text-primary" />
                                <h2 className="text-base font-bold text-foreground">
                                    {locale === 'bn' ? 'সাম্প্রতিক মাসিক ইনভয়েস' : 'Recent Monthly Invoices'}
                                </h2>
                            </div>
                        </div>

                        {recentInvoices.length === 0 ? (
                            <div className="flex flex-1 flex-col items-center justify-center gap-2 p-10 text-center">
                                <Receipt className="size-8 text-muted-foreground/50" />
                                <p className="text-sm font-medium text-muted-foreground">
                                    {locale === 'bn'
                                        ? 'এখনও কোনো মাসিক ইনভয়েস তৈরি হয়নি'
                                        : 'No monthly invoices generated yet'}
                                </p>
                            </div>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-muted/60 text-xs font-semibold text-muted-foreground">
                                        <tr>
                                            <th className="px-5 py-3">
                                                {locale === 'bn' ? 'ইনভয়েস নং' : 'Invoice ID'}
                                            </th>
                                            <th className="px-5 py-3">
                                                {locale === 'bn' ? 'শিক্ষার্থী' : 'Student'}
                                            </th>
                                            <th className="px-5 py-3 text-right">
                                                {locale === 'bn' ? 'মোট' : 'Total'}
                                            </th>
                                            <th className="px-5 py-3 text-right">
                                                {locale === 'bn' ? 'বকেয়া' : 'Due'}
                                            </th>
                                            <th className="px-5 py-3">
                                                {t('common.status', 'Status')}
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {recentInvoices.map((inv) => (
                                            <tr key={inv.id} className="hover:bg-muted/30">
                                                <td className="px-5 py-3 font-medium text-foreground">
                                                    <Link href={showInvoice(inv.id)} className="text-primary hover:underline">
                                                        {inv.invoice_number}
                                                    </Link>
                                                </td>
                                                <td className="px-5 py-3 text-foreground">
                                                    {inv.student
                                                        ? localized(inv.student, 'name')
                                                        : '—'}
                                                </td>
                                                <td className="px-5 py-3 text-right tabular-nums">
                                                    {formatBdt(inv.total_amount)}
                                                </td>
                                                <td className="px-5 py-3 text-right font-semibold tabular-nums">
                                                    {formatBdt(inv.due_amount)}
                                                </td>
                                                <td className="px-5 py-3">
                                                    <span
                                                        className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold ${
                                                            statusPillClasses[inv.status] ??
                                                            'bg-muted text-muted-foreground'
                                                        }`}
                                                    >
                                                        {t(`status.${inv.status}`, inv.status)}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>

                    <div className="minimal-card flex flex-col">
                        <div className="flex items-center gap-2 border-b border-border px-5 py-4">
                            <HeartHandshake className="size-4 text-primary" />
                            <h2 className="text-base font-bold text-foreground">
                                {locale === 'bn' ? 'সক্রিয় অনুদান ফান্ড' : 'Active Donation Funds'}
                            </h2>
                        </div>
                        <div className="divide-y divide-border p-2">
                            {donationFunds.length === 0 ? (
                                <p className="p-6 text-center text-sm text-muted-foreground">
                                    {locale === 'bn' ? 'কোনো ফান্ড পাওয়া যায়নি' : 'No funds found'}
                                </p>
                            ) : (
                                donationFunds.map((fund) => (
                                    <div
                                        key={fund.id}
                                        className="flex items-center justify-between rounded-xl px-3 py-3 hover:bg-muted/40"
                                    >
                                        <div>
                                            <p className="text-sm font-semibold text-foreground">
                                                {localized(fund, 'name')}
                                            </p>
                                            <p className="text-xs text-muted-foreground">
                                                {fund.code}
                                            </p>
                                        </div>
                                        <div className="text-right">
                                            <p className="text-sm font-bold tabular-nums text-foreground">
                                                {formatBdt(fund.balance)}
                                            </p>
                                            <span
                                                className={`inline-block rounded-full px-2 py-0.5 text-[10px] font-semibold ${
                                                    fund.is_restricted
                                                        ? 'bg-[#8E33FF]/12 text-[#8E33FF] dark:text-[#C684FF]'
                                                        : 'bg-[#00A76F]/12 text-[#00A76F]'
                                                }`}
                                            >
                                                {fund.is_restricted
                                                    ? locale === 'bn'
                                                        ? 'সংরক্ষিত'
                                                        : 'Restricted'
                                                    : locale === 'bn'
                                                      ? 'সাধারণ'
                                                      : 'General'}
                                            </span>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

Dashboard.layout = {
    breadcrumbs: [
        {
            title: 'Dashboard',
            href: dashboard(),
        },
    ],
};
