'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout'; // Assuming this is your layout component
import { CheckIcon, XMarkIcon } from '@heroicons/react/20/solid';
import { Head, router, useForm } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import Confetti from 'react-confetti';
import { useWindowSize } from 'react-use';
import { toast } from 'sonner';

export default function DataAnggotaList({
    // Receive the full pagination object
    anggotas,
    // Receive search and sumber from props as passed by the controller
    search: initialSearch = '',
    sumber: initialSumber = '',
}) {
    const { width, height } = useWindowSize();
    const [showAddModal, setShowAddModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [showQrModal, setShowQrModal] = useState(false);
    const [currentQrCodeUrl, setCurrentQrCodeUrl] = useState('');
    const [success, setSuccess] = useState(false);
    const [searchTerm, setSearchTerm] = useState(initialSearch);
    const [filterSumber, setFilterSumber] = useState(initialSumber);

    const {
        data,
        setData,
        post,
        processing,
        errors,
        reset,
        delete: inertiaDelete,
        put,
    } = useForm({
        id: null,
        nama: '',
        no_wa: '',
        email: '',
        nama_perusahaan: '',
        alamat: '',
        sumber: '',
        wa_sent: '',
        email_sent: '',
    });

    // Destructure pagination properties from the 'anggotas' object
    // This is the CRUCIAL part for displaying data correctly
    const anggotasData = anggotas.data || []; // Array of members
    const current_page = anggotas.current_page;
    const last_page = anggotas.last_page;
    const from = anggotas.from;
    const to = anggotas.to;
    const total = anggotas.total;
    const links = anggotas.links; // Pagination links

    // Handle form submission for adding new member
    const handleSubmit = (e) => {
        e.preventDefault();
        post('/data-anggota', {
            onSuccess: () => {
                setSuccess(true);
                toast.success('Anggota berhasil ditambahkan!');
                reset();
                setShowAddModal(false); // Close modal on success
                // Fetch the updated list from the server to reflect changes and correct pagination
                router.get(
                    route('data-anggota.index'),
                    { search: searchTerm, sumber: filterSumber }, // Pass current filters
                    { preserveState: true, replace: true },
                );
            },
            onError: (errors) => {
                console.error(errors);
                toast.error('Terjadi kesalahan saat menambahkan anggota!');
            },
        });
    };

    // Handle form submission for updating member
    const handleUpdate = (e) => {
        e.preventDefault();
        put(`/data-anggota/${data.id}`, {
            onSuccess: () => {
                toast.success('Anggota berhasil diupdate!');
                setShowEditModal(false);
                reset();
                // Fetch the updated list from the server
                router.get(
                    route('data-anggota.index'),
                    { search: searchTerm, sumber: filterSumber }, // Pass current filters
                    { preserveState: true, replace: true },
                );
            },
            onError: (errors) => {
                console.error(errors);
                toast.error('Terjadi kesalahan saat mengupdate anggota!');
            },
        });
    };

    // Handle member deletion
    const handleDelete = (id) => {
        if (confirm('Apakah Anda yakin ingin menghapus anggota ini?')) {
            inertiaDelete(`/data-anggota/${id}`, {
                onSuccess: () => {
                    toast.success('Anggota berhasil dihapus!');
                    // Fetch the updated list from the server
                    router.get(
                        route('data-anggota.index'),
                        { search: searchTerm, sumber: filterSumber }, // Pass current filters
                        { preserveState: true, replace: true },
                    );
                },
                onError: (errors) => {
                    console.error(errors);
                    toast.error('Terjadi kesalahan saat menghapus anggota!');
                },
            });
        }
    };

    // Handle edit button click
    const handleEditClick = (anggota) => {
        setData({
            id: anggota.id,
            nama: anggota.nama || '',
            no_kta: anggota.no_kta || '',
            no_wa: anggota.no_wa || '',
            email: anggota.email || '',
            nama_perusahaan: anggota.nama_perusahaan || '',
            alamat: anggota.alamat || '',
            sumber: anggota.sumber || '',
        });
        setShowEditModal(true);
    };

    // Handle QR code viewing
    const handleViewQrCode = (qrCodePath) => {
        if (qrCodePath) {
            const fullUrl = `/storage/${qrCodePath}`;
            setCurrentQrCodeUrl(fullUrl);
            setShowQrModal(true);
        } else {
            toast.info('QR Code belum tersedia untuk anggota ini.');
        }
    };

    // Handle pagination - important to pass current search/filter state
    const handlePageChange = (url) => {
        if (url) {
            router.get(
                url,
                { search: searchTerm, sumber: filterSumber }, // Pass current filters
                { preserveState: true, replace: true },
            );
        }
    };

    // Handle search - always trigger server-side search
    const handleSearch = (e) => {
        const term = e.target.value;
        setSearchTerm(term); // Update local state immediately for input field
        router.get(route('data-anggota.index'), { search: term, sumber: filterSumber }, { preserveState: true, replace: true });
    };

    // Handle filter change - always trigger server-side filter
    const handleFilterChange = (e) => {
        const value = e.target.value;
        setFilterSumber(value); // Update local state immediately for select field
        router.get(route('data-anggota.index'), { search: searchTerm, sumber: value }, { preserveState: true, replace: true });
    };

    useEffect(() => {
        if (success) {
            const timer = setTimeout(() => {
                setShowAddModal(false);
                setSuccess(false);
            }, 5000);
            return () => clearTimeout(timer);
        }
    }, [success]);

    return (
        <AppLayout>
            <Head title="Data Anggota" />
            <div className="space-y-6 p-4">
                <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 Data Anggota</h2>
                        <p className="text-sm text-gray-600">
                            Menampilkan {from} sampai {to} dari {total} anggota
                        </p>
                    </div>
                    <Button onClick={() => setShowAddModal(true)} className="rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700">
                        + Tambah Anggota
                    </Button>
                </div>

                {/* Search and Filter Section */}
                <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 Anggota
                        </Label>
                        <Input
                            id="search"
                            type="text"
                            placeholder="Cari berdasarkan nama, KTA, WA, perusahaan, alamat, atau sumber..."
                            value={searchTerm}
                            onChange={handleSearch}
                            className="w-full rounded-md border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        />
                    </div>
                    <div className="w-full sm:w-auto">
                        <Label htmlFor="filter-sumber" className="sr-only">
                            Filter Sumber
                        </Label>
                        <select
                            id="filter-sumber"
                            value={filterSumber}
                            onChange={handleFilterChange}
                            className="w-full rounded-md border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        >
                            <option value="">Semua Sumber</option>
                            <option value="panitia">Panitia</option>
                            <option value="voter">Voter</option>
                            <option value="peninjau">Peninjau</option>
                            {/* Tambahkan sumber lain sesuai kebutuhan */}
                        </select>
                    </div>
                </div>

                {/* Members Table */}
                <div className="overflow-auto rounded-lg border border-gray-200 shadow-sm">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    No
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    Nama
                                </th>

                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    WhatsApp
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    Email
                                </th>

                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    Sumber
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    WhatsApp Send
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    Mail Send
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase">
                                    Aksi
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-200 bg-white">
                            {anggotasData.length > 0 ? (
                                anggotasData.map((anggota, index) => (
                                    <tr key={anggota.id} className="hover:bg-gray-50">
                                        <td className="px-6 py-4 text-sm whitespace-nowrap text-gray-500">
                                            {from + index} {/* Correct numbering for server-side pagination */}
                                        </td>
                                        <td className="px-6 py-4 text-sm font-medium whitespace-nowrap text-gray-900">{anggota.nama}</td>
                                        <td className="px-6 py-4 text-sm whitespace-nowrap text-gray-500">{anggota.no_wa}</td>
                                        <td className="px-6 py-4 text-sm whitespace-nowrap text-gray-500">{anggota.email}</td>
                                        <td className="px-6 py-4 text-sm whitespace-nowrap text-gray-500">{anggota.sumber || '-'}</td>
                                        <td className="px-6 py-4 text-center text-sm whitespace-nowrap text-gray-500">
                                            {anggota.wa_sent === 1 ? (
                                                <CheckIcon className="mx-auto h-5 w-5 text-green-500" />
                                            ) : (
                                                <XMarkIcon className="mx-auto h-5 w-5 text-red-500" />
                                            )}
                                        </td>{' '}
                                        <td className="px-6 py-4 text-center text-sm whitespace-nowrap text-gray-500">
                                            {anggota.email_sent === 1 ? (
                                                <CheckIcon className="mx-auto h-5 w-5 text-green-500" />
                                            ) : (
                                                <XMarkIcon className="mx-auto h-5 w-5 text-red-500" />
                                            )}
                                        </td>{' '}
                                        <td className="px-6 py-4 text-sm whitespace-nowrap text-gray-500">
                                            <div className="space-s-1 flex">
                                                <Button
                                                    onClick={() => handleEditClick(anggota)}
                                                    variant="outline" // Use outline variant for a subtle look
                                                    className="text-indigo-600 hover:bg-indigo-50" // Keep text color, add light background on hover
                                                >
                                                    Edit
                                                </Button>
                                                <Button
                                                    onClick={() => handleDelete(anggota.id)}
                                                    variant="outline" // Use outline variant
                                                    className="text-red-600 hover:bg-red-50" // Keep text color, add light background on hover
                                                >
                                                    Hapus
                                                </Button>
                                                <Button
                                                    onClick={() => handleViewQrCode(anggota.qr_code_path)}
                                                    variant="outline" // Use outline variant
                                                    className="text-green-600 hover:bg-green-50" // Keep text color, add light background on hover
                                                >
                                                    QR
                                                </Button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            ) : (
                                <tr>
                                    <td colSpan="8" className="px-6 py-4 text-center text-sm text-gray-500">
                                        Tidak ada data anggota yang cocok dengan pencarian atau filter Anda.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Pagination */}
                {total > 0 && last_page > 1 && (
                    <div className="flex items-center justify-between">
                        <div className="text-sm text-gray-700">
                            Halaman <span className="font-medium">{current_page}</span> dari <span className="font-medium">{last_page}</span>
                        </div>
                        <div className="flex space-x-2">
                            {links.map((link, index) => (
                                // Use link.url directly for pagination, and decode HTML entities if present
                                <Button
                                    key={index}
                                    onClick={() => handlePageChange(link.url)}
                                    disabled={!link.url || link.active} // Disable if no URL or if it's the active page
                                    variant="outline"
                                    className={`${!link.url || link.active ? 'cursor-not-allowed opacity-50' : ''}`}
                                >
                                    <span dangerouslySetInnerHTML={{ __html: link.label }} />
                                </Button>
                            ))}
                        </div>
                    </div>
                )}

                {/* Add Member Modal */}
                {showAddModal && (
                    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
                        <motion.div
                            initial={{ scale: 0.8, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            transition={{ duration: 0.3 }}
                            className="relative w-full max-w-lg rounded-2xl bg-white p-8 shadow-2xl"
                        >
                            {success && <Confetti width={width} height={height} numberOfPieces={200} className="absolute inset-0 m-auto" />}
                            <h2 className="mb-6 text-center text-3xl font-extrabold text-blue-700">Tambah Anggota Baru</h2>
                            <form onSubmit={handleSubmit} className="space-y-6">
                                <div>
                                    <Label htmlFor="nama" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nama
                                    </Label>
                                    <Input
                                        id="nama"
                                        value={data.nama}
                                        onChange={(e) => setData('nama', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.nama && <div className="mt-1 text-sm text-red-500">{errors.nama}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="no_kta" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nomor KTA
                                    </Label>
                                    <Input id="no_kta" value={data.no_kta} onChange={(e) => setData('no_kta', e.target.value)} className="w-full" />
                                    {errors.no_kta && <div className="mt-1 text-sm text-red-500">{errors.no_kta}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="no_wa" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nomor WhatsApp
                                    </Label>
                                    <Input
                                        id="no_wa"
                                        value={data.no_wa}
                                        onChange={(e) => setData('no_wa', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.no_wa && <div className="mt-1 text-sm text-red-500">{errors.no_wa}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="email" className="mb-2 block text-sm font-bold text-gray-700">
                                        Email
                                    </Label>
                                    <Input
                                        id="no_wa"
                                        value={data.email}
                                        onChange={(e) => setData('email', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.email && <div className="mt-1 text-sm text-red-500">{errors.email}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="nama_perusahaan" className="mb-2 block text-sm font-bold text-gray-700">
                                        Perusahaan
                                    </Label>
                                    <Input
                                        id="nama_perusahaan"
                                        value={data.nama_perusahaan}
                                        onChange={(e) => setData('nama_perusahaan', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.nama_perusahaan && <div className="mt-1 text-sm text-red-500">{errors.nama_perusahaan}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="alamat" className="mb-2 block text-sm font-bold text-gray-700">
                                        Alamat
                                    </Label>
                                    <Input id="alamat" value={data.alamat} onChange={(e) => setData('alamat', e.target.value)} className="w-full" />
                                    {errors.alamat && <div className="mt-1 text-sm text-red-500">{errors.alamat}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="sumber" className="mb-2 block text-sm font-bold text-gray-700">
                                        Sumber
                                    </Label>
                                    <select
                                        id="sumber"
                                        value={data.sumber}
                                        onChange={(e) => setData('sumber', e.target.value)}
                                        required
                                        className="w-full rounded-md border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                    >
                                        <option value="">Pilih Sumber</option>
                                        <option value="panitia">Panitia</option>
                                        <option value="voter">Voter</option>
                                        <option value="peninjau">Peninjau</option>
                                    </select>
                                    {errors.sumber && <div className="mt-1 text-sm text-red-500">{errors.sumber}</div>}
                                </div>
                                <div className="flex space-x-4">
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        className="w-full rounded-md bg-blue-600 py-3 font-semibold text-white transition duration-300 ease-in-out hover:bg-blue-700"
                                    >
                                        {processing ? 'Menyimpan...' : 'Simpan'}
                                    </Button>
                                    <Button
                                        type="button"
                                        onClick={() => setShowAddModal(false)}
                                        className="w-full rounded-md bg-gray-600 py-3 font-semibold text-white transition duration-300 ease-in-out hover:bg-gray-700"
                                    >
                                        Batal
                                    </Button>
                                </div>
                            </form>
                        </motion.div>
                    </div>
                )}

                {/* Edit Member Modal */}
                {showEditModal && (
                    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
                        <motion.div
                            initial={{ scale: 0.8, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            transition={{ duration: 0.3 }}
                            className="relative w-full max-w-lg rounded-2xl bg-white p-8 shadow-2xl"
                        >
                            <h2 className="mb-6 text-center text-3xl font-extrabold text-green-700">Edit Anggota</h2>
                            <form onSubmit={handleUpdate} className="space-y-6">
                                <div>
                                    <Label htmlFor="edit-nama" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nama
                                    </Label>
                                    <Input
                                        id="edit-nama"
                                        value={data.nama}
                                        onChange={(e) => setData('nama', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.nama && <div className="mt-1 text-sm text-red-500">{errors.nama}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-no_kta" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nomor KTA
                                    </Label>
                                    <Input
                                        id="edit-no_kta"
                                        value={data.no_kta}
                                        onChange={(e) => setData('no_kta', e.target.value)}
                                        className="w-full"
                                    />
                                    {errors.no_kta && <div className="mt-1 text-sm text-red-500">{errors.no_kta}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-no_wa" className="mb-2 block text-sm font-bold text-gray-700">
                                        Nomor WhatsApp
                                    </Label>
                                    <Input
                                        id="edit-no_wa"
                                        value={data.no_wa}
                                        onChange={(e) => setData('no_wa', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.no_wa && <div className="mt-1 text-sm text-red-500">{errors.no_wa}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-email" className="mb-2 block text-sm font-bold text-gray-700">
                                        Email
                                    </Label>
                                    <Input
                                        id="edit-email"
                                        value={data.email}
                                        onChange={(e) => setData('email', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.email && <div className="mt-1 text-sm text-red-500">{errors.email}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-nama_perusahaan" className="mb-2 block text-sm font-bold text-gray-700">
                                        Perusahaan
                                    </Label>
                                    <Input
                                        id="edit-nama_perusahaan"
                                        value={data.nama_perusahaan}
                                        onChange={(e) => setData('nama_perusahaan', e.target.value)}
                                        required
                                        className="w-full"
                                    />
                                    {errors.nama_perusahaan && <div className="mt-1 text-sm text-red-500">{errors.nama_perusahaan}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-alamat" className="mb-2 block text-sm font-bold text-gray-700">
                                        Alamat
                                    </Label>
                                    <Input
                                        id="edit-alamat"
                                        value={data.alamat}
                                        onChange={(e) => setData('alamat', e.target.value)}
                                        className="w-full"
                                    />
                                    {errors.alamat && <div className="mt-1 text-sm text-red-500">{errors.alamat}</div>}
                                </div>
                                <div>
                                    <Label htmlFor="edit-sumber" className="mb-2 block text-sm font-bold text-gray-700">
                                        Sumber
                                    </Label>
                                    <select
                                        id="edit-sumber"
                                        value={data.sumber}
                                        onChange={(e) => setData('sumber', e.target.value)}
                                        required
                                        className="w-full rounded-md border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                    >
                                        <option value="">Pilih Sumber</option>
                                        <option value="panitia">Panitia</option>
                                        <option value="voter">Voter</option>
                                        <option value="peninjau">Peninjau</option>
                                    </select>
                                    {errors.sumber && <div className="mt-1 text-sm text-red-500">{errors.sumber}</div>}
                                </div>
                                <div className="flex space-x-4">
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        className="w-full rounded-md bg-green-600 py-3 font-semibold text-white transition duration-300 ease-in-out hover:bg-green-700"
                                    >
                                        {processing ? 'Mengupdate...' : 'Update'}
                                    </Button>
                                    <Button
                                        type="button"
                                        onClick={() => setShowEditModal(false)}
                                        className="w-full rounded-md bg-gray-600 py-3 font-semibold text-white transition duration-300 ease-in-out hover:bg-gray-700"
                                    >
                                        Batal
                                    </Button>
                                </div>
                            </form>
                        </motion.div>
                    </div>
                )}

                {/* QR Code Modal */}
                {showQrModal && (
                    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
                        <motion.div
                            initial={{ scale: 0.8, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            transition={{ duration: 0.3 }}
                            className="relative w-full max-w-sm rounded-2xl bg-white p-6 text-center shadow-2xl"
                        >
                            <h2 className="mb-4 text-2xl font-bold text-gray-800">QR Code Anggota</h2>
                            {currentQrCodeUrl ? (
                                <img
                                    src={currentQrCodeUrl}
                                    alt="QR Code"
                                    className="mx-auto h-48 w-48 rounded-md border border-gray-300 object-contain"
                                />
                            ) : (
                                <p className="text-gray-600">Tidak ada QR Code.</p>
                            )}
                            <Button
                                onClick={() => setShowQrModal(false)}
                                className="mt-6 rounded-md bg-red-600 px-4 py-2 text-white hover:bg-red-700"
                            >
                                Tutup
                            </Button>
                        </motion.div>
                    </div>
                )}
            </div>
        </AppLayout>
    );
}
