import StyledTable from "@/Components/Admin/ui/StyledTable";
import { useEffect, useState, useRef } from "react";
import { Link, router, usePage } from '@inertiajs/react';
import { toast, Toaster } from "react-hot-toast";
import ViewPayment from "./ViewPayment";

export default function DueTodayPayments({ payments }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [paymentData, setPaymentData] = useState([]);
    const [isViewModalOpen, setIsViewModalOpen] = useState(false);
    const [selectedPayment, setSelectedPayment] = useState(null);

    // Handle flash messages
    useEffect(() => {
        if (flash?.success) {
            const message = typeof flash.success === 'object' ? flash.success.message : flash.success;
            if (message && !processedMessages.current.has(`success-${message}`)) {
                toast.success(message);
                processedMessages.current.add(`success-${message}`);
            }
        }
        if (flash?.error) {
            const message = typeof flash.error === 'object' ? flash.error.message : flash.error;
            if (message && !processedMessages.current.has(`error-${message}`)) {
                toast.error(message);
                processedMessages.current.add(`error-${message}`);
            }
        }
    }, [flash]);

    useEffect(() => {
        setPaymentData(payments || []);
    }, [payments]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'tenant_name', header: 'Tenant' },
        { key: 'landlord_name', header: 'Landlord' },
        { key: 'amount', header: 'Amount' },
        { key: 'payment_type', header: 'Type' },
        { key: 'payment_method', header: 'Method' },
        { key: 'due_date', header: 'Due Date' },
        { key: 'status', header: 'Status' }
    ];

    const transformedData = paymentData.map(payment => ({
        ...payment,
        amount: `$${payment.amount || '0.00'}`,
        status: (
            <span className={`badge badge-${payment.status_badge || 'warning'}`}>
                {payment.status?.charAt(0).toUpperCase() + payment.status?.slice(1) || 'Pending'}
            </span>
        ),
    }));

    const handleView = (row) => {
        fetch(`/admin/payments/${row.id}`)
            .then((response) => response.json())
            .then((paymentData) => {
                setSelectedPayment(paymentData);
                setIsViewModalOpen(true);
            })
            .catch((error) => {
                console.error('Error:', error);
                toast.error('Failed to load payment details');
            });
    };

    return (
        <>
            <Toaster />
            <div className="row">
                <div className="col-lg-12 mt-4">
                    <div className="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h4 className="header-title">Payments Due Today</h4>
                            <p className="text-muted">Payments that are due today</p>
                        </div>
                        <div>
                            <Link href="/admin/payments" className="btn btn-secondary mr-2">
                                <i className="ti-list mr-2"></i>
                                All Payments
                            </Link>
                            <Link href="/admin/payments/overdue" className="btn btn-danger">
                                <i className="ti-alert mr-2"></i>
                                Overdue
                            </Link>
                        </div>
                    </div>
                    {paymentData.length === 0 ? (
                        <div className="alert alert-info">
                            <i className="ti-info-alt mr-2"></i>
                            No payments due today.
                        </div>
                    ) : (
                        <div className="single-table">
                            <div className="table-responsive">
                                <table className="table table-hover text-center">
                                    <thead className="bg-light text-capitalize">
                                        <tr>
                                            {columns.map((column, index) => (
                                                <th key={index} scope="col">{column.header}</th>
                                            ))}
                                            <th scope="col">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {transformedData.map((payment, index) => (
                                            <tr key={payment.id}>
                                                <td>{payment.sn}</td>
                                                <td>{payment.tenant_name}</td>
                                                <td>{payment.landlord_name}</td>
                                                <td>{payment.amount}</td>
                                                <td>{payment.payment_type}</td>
                                                <td>{payment.payment_method}</td>
                                                <td>{payment.due_date}</td>
                                                <td>{payment.status}</td>
                                                <td>
                                                    <ul className="d-flex justify-content-center">
                                                        <li>
                                                            <a
                                                                href="#"
                                                                className="text-info"
                                                                onClick={(e) => {
                                                                    e.preventDefault();
                                                                    handleView(payment);
                                                                }}
                                                                title="View"
                                                            >
                                                                <i className="fa fa-eye"></i>
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            <ViewPayment
                isOpen={isViewModalOpen}
                onClose={() => setIsViewModalOpen(false)}
                payment={selectedPayment}
            />
        </>
    );
}

