import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import ModalInput from '@/Components/ModalInput';
import { useDispatch } from 'react-redux';
import { setPageTitle } from '@/Components/features/common/headerSlice';
import { CurrencyDollarIcon } from '@heroicons/react/24/outline'
import { usePage } from '@inertiajs/react';
import Swal from "sweetalert2"


export default function ManualPayment({ santri, fields, options }) {
    const [selectedSantri, setSelectedSantri] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredSantri, setFilteredSantri] = useState([]);
    const [selectedPayments, setSelectedPayments] = useState(null);
    const { flash } = usePage().props;

    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(setPageTitle("Data Payment"));
    }, [dispatch]);

    // console.log(santri.id)
    useEffect(() => {
        if (santri?.data) {
            if (santri?.data) {
                const filtered = santri.data.filter(item =>
                    item.nama.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    item.nis.toString().includes(searchTerm)
                );
                setFilteredSantri(filtered);
            }
        }
    }, [searchTerm, santri]);

    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
    };

    const monthNames = [
        "Januari", "Februari", "Maret", "April", "Mei", "Juni",
        "Juli", "Agustus", "September", "Oktober", "November", "Desember"
    ];



    return (
        <div>
            <Head title="Manual Payment" />
            <ModalInput
                showPayments={true}
                fields={fields}
                options={options}
                tableName="payments"
                initialData={selectedSantri}
                onClose={() => setSelectedSantri(null)}
            />

            <div className="card bg-base-100 shadow-xl">
                <div className="card-body">
                    <div className="flex items-center mb-6">
                        <div className="bg-gradient-to-tr from-blue-400 to-blue-600 p-3 rounded-lg mr-3">
                            <CurrencyDollarIcon className="h-6 w-6 text-white" />
                        </div>
                        <h1 className="text-2xl font-bold">Data Pembayaran</h1>
                        <div className="ml-auto">
                            <span className="text-gray-700">Overview</span>
                            <span className="ml-2 text-gray-500">
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 inline" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </span>
                        </div>
                    </div>
                    <div className="flex justify-between items-center mb-4">
                        <div className="form-control">
                            <div className="input-group">
                                <input
                                    type="text"
                                    placeholder="Cari Santri..."
                                    className="input input-bordered"
                                    value={searchTerm}
                                    onChange={handleSearch}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="table table-zebra w-full">
                            <thead>
                                <tr>
                                    <th>Nama</th>
                                    <th>Nis</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredSantri.length > 0 ? (
                                    filteredSantri.map((item, i) => (
                                        <tr key={i}>
                                            <td>
                                                <div className="flex items-center space-x-3">
                                                    <div className="avatar">
                                                        <div className="mask mask-squircle w-12 h-12">
                                                            <img src={`https://ui-avatars.com/api/?name=${item.nama}`} alt="Avatar" />
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div className="font-bold">{item.nama}</div>
                                                        <div className="text-sm opacity-50">{item.level == 1 ? 'Admin' : 'User'}</div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>{item.nis}</td>
                                            <td>
                                                <div className={`badge ${item.status_santri === 'aktif' ? 'badge-success' : 'badge-warning'} gap-2 text-white`}>
                                                    {item.status_santri || "Open"}
                                                </div>
                                            </td>
                                            <td>
                                                <div className="flex space-x-2">
                                                    <button
                                                        className="btn btn-sm btn-accent text-white"
                                                        onClick={() => {
                                                            setSelectedSantri({
                                                                id: item.id,
                                                                nama: item.nama,
                                                                nis: item.nis,
                                                                status_santri: item.status_santri,
                                                                role_santri: item.role_santri
                                                            });
                                                            document.getElementById('modal_input').checked = true;
                                                        }}
                                                    >
                                                        Bayar
                                                    </button>
                                                    <button
                                                        className="btn btn-sm btn-primary text-white"
                                                        onClick={() => setSelectedPayments(item.payments)}
                                                    >
                                                        Show Pembayaran
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="4" className="text-center">Tidak ada data santri.</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                    <div className="flex justify-center mt-4">
                        {santri.current_page > 1 && (
                            <button className="btn btn-sm mx-1" onClick={() => (window.location.href = `?page=1`)}>
                                &laquo;
                            </button>
                        )}
                        {santri.current_page > 3 && (
                            <span className="btn btn-sm mx-1 pointer-events-none">...</span>
                        )}

                        {Array.from({ length: santri.last_page }, (_, i) => i + 1)
                            .filter((page) =>
                                page === 1 ||
                                page === santri.last_page ||
                                Math.abs(page - santri.current_page) <= 2
                            )
                            .map((page) => (
                                <button
                                    key={page}
                                    className={`btn btn-sm mx-1 ${santri.current_page === page ? 'btn-active btn-primary text-white' : ''}`}
                                    onClick={() => {
                                        window.location.href = `?page=${page}`;
                                    }}
                                >
                                    {page}
                                </button>
                            ))}

                        {santri.current_page < santri.last_page - 2 && (
                            <span className="btn btn-sm mx-1 pointer-events-none">...</span>
                        )}
                        {santri.current_page < santri.last_page && (
                            <button className="btn btn-sm mx-1" onClick={() => (window.location.href = `?page=${santri.last_page}`)}>
                                &raquo;
                            </button>
                        )}
                    </div>

                </div>
            </div>

            {selectedPayments && (
                <div>
                    <input type="checkbox" id="modal_show_payments" className="modal-toggle" defaultChecked />
                    <div className="modal" role="dialog">
                        <div className="modal-box">
                            <h3 className="text-lg font-bold">Riwayat Pembayaran</h3>
                            <div className="overflow-x-auto">
                                <table className="table">
                                    <thead>
                                        <tr>
                                            <th>Tipe Pembayaran</th>
                                            <th>Tahun</th>
                                            <th>Bulan</th>
                                            <th>Denda</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {selectedPayments.map((payment, idx) =>
                                            payment.detail_payments.map((detail) => (
                                                <tr key={`${idx}-${detail.id}`}>
                                                    <td>{detail.payment_type?.payment_type}</td>
                                                    <td className="text-center">{detail.payment_year}</td>
                                                    <td className="text-center">{monthNames[detail.payment_month - 1] || detail.payment_month}</td>
                                                    <td className="text-center">{detail.penalty}</td>
                                                    <td className="text-center">
                                                        <span className={`p-2 rounded-md ${detail.status === 'paid' ? 'bg-green-500 text-white' : 'bg-red-600 text-white'}`}>
                                                            {detail.status}
                                                        </span>
                                                    </td>
                                                </tr>
                                            ))
                                        )}

                                    </tbody>
                                </table>
                            </div>
                            {/* <div className="modal-action">
                                <label className="btn" onClick={() => setSelectedPayments(null)}>
                                    Tutup
                                </label>
                            </div> */}
                        </div>
                        <label className="modal-backdrop" htmlFor="modal_show_payments" onClick={() => setSelectedPayments(null)}></label>
                    </div>
                </div>
            )}
        </div>
    );
}
