import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import { Head } from '@inertiajs/react';
import { saveAs } from 'file-saver';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import { useMemo, useState } from 'react';
import * as XLSX from 'xlsx';

interface KehadiranItem {
    id: number;
    anggota_nama: string;
    anggota_no_wa?: string;
    anggota_sumber?: string;
    anggota_alamat?: string;
    waktu_hadir?: string;
    status: 'Hadir' | 'Tidak Hadir';
}

interface Props {
    kehadiranData: KehadiranItem[];
    currentDate: string;
}

export default function DaftarKehadiran({ kehadiranData, currentDate }: Props) {
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('');

    const filteredData = useMemo(() => {
        return kehadiranData
            .filter((item) => item.anggota_nama.toLowerCase().includes(searchTerm.toLowerCase()))
            .filter((item) => (statusFilter ? item.status === statusFilter : true));
    }, [kehadiranData, searchTerm, statusFilter]);

    const exportPDF = () => {
        const doc = new jsPDF();
        autoTable(doc, {
            head: [['No', 'Nama', 'KTA', 'WA', 'Perusahaan', 'Alamat', 'Sumber', 'Waktu Hadir', 'Status']],
            body: filteredData.map((item, idx) => [
                idx + 1,
                item.anggota_nama,
                item.anggota_no_wa || '-',
                item.anggota_sumber || '-',
                item.anggota_alamat || '-',
                item.waktu_hadir || '-',
                item.status,
            ]),
        });
        doc.save('kehadiran.pdf');
    };

    const exportExcel = () => {
        const ws = XLSX.utils.json_to_sheet(
            filteredData.map((item, idx) => ({
                No: idx + 1,
                Nama: item.anggota_nama,
                WA: item.anggota_no_wa || '-',
                Sumber: item.anggota_sumber || '-',
                Alamat: item.anggota_alamat || '-',
                'Waktu Hadir': item.waktu_hadir || '-',
                Status: item.status,
            })),
        );

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Kehadiran');
        const buffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'kehadiran.xlsx');
    };

    return (
        <AppLayout>
            <Head title="Daftar Kehadiran" />
            <div className="space-y-6 p-4">
                {/* Header Section */}
                <div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
                    <div>
                        <h2 className="text-2xl font-semibold text-gray-800">Daftar Hadir</h2>
                        <p className="text-sm text-gray-600">Tanggal: {currentDate}</p>
                        <p className="text-sm text-gray-600">Total: {filteredData.length} anggota</p>
                    </div>
                    <div className="flex gap-2">
                        <Button className="bg-green-600 text-white hover:bg-green-700" onClick={exportExcel}>
                            📊 Export Excel
                        </Button>
                        <Button className="bg-red-600 text-white hover:bg-red-700" onClick={exportPDF}>
                            📄 Export PDF
                        </Button>
                    </div>
                </div>

                {/* Search & Filter */}
                <div className="flex flex-col items-center gap-4 sm:flex-row">
                    <div className="w-full sm:w-1/2">
                        <Label htmlFor="search" className="sr-only">
                            Cari
                        </Label>
                        <Input id="search" placeholder="Cari nama anggota..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                    </div>
                    <div className="w-full sm:w-auto">
                        <select
                            value={statusFilter}
                            onChange={(e) => setStatusFilter(e.target.value)}
                            className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        >
                            <option value="">Semua Status</option>
                            <option value="Hadir">Hadir</option>
                            <option value="Tidak Hadir">Tidak Hadir</option>
                        </select>
                    </div>
                </div>

                {/* Tabel Kehadiran */}
                <div className="overflow-auto rounded-lg border border-gray-200 shadow-sm">
                    <table className="min-w-full divide-y divide-gray-200 text-sm">
                        <thead className="bg-gray-50 text-xs text-gray-500 uppercase">
                            <tr>
                                <th className="px-6 py-3 text-left">No</th>
                                <th className="px-6 py-3 text-left">Nama</th>
                                <th className="px-6 py-3 text-left">WA</th>
                                <th className="px-6 py-3 text-left">Sumber</th>
                                <th className="px-6 py-3 text-left">Waktu Hadir</th>
                                <th className="px-6 py-3 text-left">Status</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100 bg-white">
                            {filteredData.length > 0 ? (
                                filteredData.map((item, index) => (
                                    <tr key={item.id} className="hover:bg-gray-50">
                                        <td className="px-6 py-4 whitespace-nowrap">{index + 1}</td>
                                        <td className="px-6 py-4">{item.anggota_nama}</td>
                                        <td className="px-6 py-4">{item.anggota_no_wa || '-'}</td>
                                        <td className="px-6 py-4">{item.anggota_sumber || '-'}</td>
                                        <td className="px-6 py-4">{item.waktu_hadir || '-'}</td>
                                        <td className="px-6 py-4">
                                            <span
                                                className={`rounded px-2 py-1 text-xs font-semibold ${item.status === 'Hadir' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}
                                            >
                                                {item.status}
                                            </span>
                                        </td>
                                    </tr>
                                ))
                            ) : (
                                <tr>
                                    <td colSpan={9} className="px-6 py-4 text-center text-gray-500">
                                        Tidak ada data kehadiran yang cocok.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </AppLayout>
    );
}
