import { Head, Link, router } from '@inertiajs/react';
import {
    Calendar,
    CheckCircle2,
    CircleDollarSign,
    ClipboardList,
    Keyboard,
    TrendingUp,
    Users,
} from 'lucide-react';

import {
    Card,
    CardAction,
    CardContent,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { usePermissions } from '@/hooks/use-permissions';
import AppLayout from '@/layouts/app-layout';
import { formatIDR } from '@/lib/formatters';
import dailyCollectionRoutes from '@/routes/daily-collection';
import type { BreadcrumbItem } from '@/types';
import type {
    CollectorSummary,
    DailyCollectionData,
} from '@/types/daily-collection';

interface PageProps {
    collectionData: DailyCollectionData;
    filters: {
        date: string;
    };
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Penagihan Harian',
        href: dailyCollectionRoutes.index().url,
    },
];

export default function Index({ collectionData, filters }: PageProps) {
    const { summary, collectors } = collectionData;
    const { hasAnyRole } = usePermissions();

    const handleDateChange = (date: string) => {
        router.get(
            dailyCollectionRoutes.index().url,
            { date },
            { preserveState: true, preserveScroll: true },
        );
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Penagihan Harian" />

            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-4">
                {/* Header */}
                <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">
                            Penagihan Harian
                        </h1>
                        <span className="text-sm text-muted-foreground">
                            Ringkasan tugas penagihan collector untuk hari ini.
                        </span>
                    </div>
                    <div className="flex items-center gap-3">
                        <div className="flex items-center gap-2">
                            <Calendar className="h-4 w-4 text-muted-foreground" />
                            <Input
                                id="date-picker"
                                type="date"
                                value={filters.date}
                                onChange={(e) =>
                                    handleDateChange(e.target.value)
                                }
                                className="w-44"
                            />
                        </div>
                        {/* Jika user role manager,admin atau teller tampilkan ini */}
                        {hasAnyRole('Manager', 'Administrator', 'Teller') && (
                            <Link
                                href={
                                    dailyCollectionRoutes.teller({
                                        query: { date: filters.date },
                                    }).url
                                }
                                className="inline-flex items-center gap-2 rounded-lg border bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
                            >
                                <Keyboard className="h-4 w-4" />
                                Mode Teller
                            </Link>
                        )}
                        {/* end of if function */}
                        <Link
                            href={dailyCollectionRoutes.performance().url}
                            className="inline-flex items-center gap-2 rounded-lg border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-muted"
                        >
                            <TrendingUp className="h-4 w-4" />
                            Laporan Performa
                        </Link>
                    </div>
                </div>

                {/* Stats Cards */}
                <div className="grid gap-4 md:grid-cols-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>Collector Aktif</CardTitle>
                            <CardAction>
                                <Users className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {summary.total_collectors}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Memiliki tugas hari ini
                            </p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Total Tugas</CardTitle>
                            <CardAction>
                                <ClipboardList className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {summary.total_tasks.toLocaleString('id-ID')}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                {summary.total_members} anggota
                            </p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Target Penagihan</CardTitle>
                            <CardAction>
                                <CircleDollarSign className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {formatIDR(summary.total_expected)}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Yang harus ditagih
                            </p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Sudah Terkumpul</CardTitle>
                            <CardAction>
                                <CheckCircle2 className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                                {formatIDR(summary.total_collected)}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                {summary.overall_completion}% tercapai
                            </p>
                        </CardContent>
                    </Card>
                </div>

                {/* Collector Table */}

                <div className="overflow-hidden rounded-xl border bg-card">
                    <table className="w-full">
                        <thead>
                            <tr className="border-b bg-muted/50">
                                <th className="px-6 py-3 text-left text-sm font-semibold">
                                    Collector
                                </th>
                                <th className="px-6 py-3 text-center text-sm font-semibold">
                                    Anggota
                                </th>
                                <th className="px-6 py-3 text-center text-sm font-semibold">
                                    Tugas
                                </th>
                                <th className="px-6 py-3 text-right text-sm font-semibold">
                                    Target
                                </th>
                                <th className="px-6 py-3 text-right text-sm font-semibold">
                                    Terkumpul
                                </th>
                                <th className="px-6 py-3 text-center text-sm font-semibold">
                                    Progress
                                </th>
                                <th className="px-6 py-3 text-center text-sm font-semibold">
                                    Aksi
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {collectors.map((collector) => (
                                <CollectorRow
                                    key={collector.collector_id}
                                    collector={collector}
                                    date={filters.date}
                                />
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </AppLayout>
    );
}

function CollectorRow({
    collector,
    date,
}: {
    collector: CollectorSummary;
    date: string;
}) {
    const completionColor =
        collector.completion_percentage >= 80
            ? 'text-emerald-600 dark:text-emerald-400'
            : collector.completion_percentage >= 50
              ? 'text-amber-600 dark:text-amber-400'
              : 'text-red-600 dark:text-red-400';

    const progressBarColor =
        collector.completion_percentage >= 80
            ? 'bg-emerald-500'
            : collector.completion_percentage >= 50
              ? 'bg-amber-500'
              : 'bg-red-500';

    return (
        <tr className="border-b transition-colors last:border-0 hover:bg-muted/30">
            <td className="px-6 py-4">
                <div className="flex items-center gap-3">
                    <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/10 text-sm font-bold text-primary">
                        {collector.collector_name.charAt(0).toUpperCase()}
                    </div>
                    <span className="font-medium">
                        {collector.collector_name}
                    </span>
                </div>
            </td>
            <td className="px-6 py-4 text-center">{collector.member_count}</td>
            <td className="px-6 py-4 text-center">
                <div className="flex flex-col items-center">
                    <span className="font-medium">{collector.task_count}</span>
                    {collector.paid_count > 0 && (
                        <span className="text-xs text-muted-foreground">
                            {collector.paid_count} selesai
                        </span>
                    )}
                </div>
            </td>
            <td className="px-6 py-4 text-right font-medium">
                {formatIDR(collector.expected_amount)}
            </td>
            <td className="px-6 py-4 text-right font-medium text-emerald-600 dark:text-emerald-400">
                {formatIDR(collector.collected_amount)}
            </td>
            <td className="px-6 py-4">
                <div className="flex flex-col items-center gap-1">
                    {collector.completion_percentage === 100 ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400">
                            <CheckCircle2 className="h-3 w-3" />
                            Semua Selesai
                        </span>
                    ) : (
                        <span
                            className={`text-sm font-bold ${completionColor}`}
                        >
                            {collector.completion_percentage}%
                        </span>
                    )}
                    <div className="h-1.5 w-16 overflow-hidden rounded-full bg-muted">
                        <div
                            className={`h-full rounded-full transition-all ${progressBarColor}`}
                            style={{
                                width: `${Math.min(collector.completion_percentage, 100)}%`,
                            }}
                        />
                    </div>
                </div>
            </td>
            <td className="px-6 py-4 text-center">
                {collector.collector_id > 0 ? (
                    <Link
                        href={
                            dailyCollectionRoutes.collectorTasks(
                                collector.collector_id,
                                { query: { date } },
                            ).url
                        }
                        className="inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90"
                    >
                        <ClipboardList className="h-3.5 w-3.5" />
                        Lihat Tugas
                    </Link>
                ) : (
                    <span className="text-xs text-muted-foreground italic">
                        Belum ditugaskan
                    </span>
                )}
            </td>
        </tr>
    );
}
