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

export default function RentalAgreement({ agreements, pagination, filters }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [agreementData, setAgreementData] = useState([]);
    const [isViewModalOpen, setIsViewModalOpen] = useState(false);
    const [selectedAgreement, setSelectedAgreement] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, agreement: null });

    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(() => {
        setAgreementData(agreements || []);
    }, [agreements]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'property_title', header: 'Property' },
        { key: 'tenant_name', header: 'Tenant' },
        { key: 'landlord_name', header: 'Landlord' },
        { key: 'start_date', header: 'Start Date' },
        { key: 'end_date', header: 'End Date' },
        { key: 'monthly_rent', header: 'Monthly Rent' },
        { key: 'is_active', header: 'Status' }
    ];

    const transformedData = agreementData.map(agreement => ({
        ...agreement,
        start_date: new Date(agreement.start_date).toLocaleDateString(),
        end_date: agreement.end_date ? new Date(agreement.end_date).toLocaleDateString() : 'N/A',
        monthly_rent: `$${agreement.monthly_rent?.toLocaleString() || '0'}`,
        is_active: agreement.is_active ? 'active' : 'inactive',
        property_title: agreement.property_title?.length > 30 ? `${agreement.property_title.substring(0, 30)}...` : agreement.property_title || 'N/A',
    }));

    const handlePageChange = (page) => {
        router.get('/admin/rental-agreements', { page }, { preserveState: true, preserveScroll: true });
    };

    const handleView = (row) => {
        fetch(`/admin/rental-agreements/${row.id}`)
            .then((response) => response.json())
            .then((agreementData) => {
                setSelectedAgreement(agreementData);
                setIsViewModalOpen(true);
            })
            .catch((error) => {
                console.error('Error:', error);
                toast.error('Failed to load rental agreement details');
            });
    };

    const handleDelete = (row) => {
        setDeleteModal({ show: true, agreement: row });
    };

    return (
        <>
            <Toaster />
            <div className="row">
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Rental Agreement Management"
                    onView={handleView}
                    onDelete={handleDelete}
                    noDataText="No rental agreements found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="rental agreements"
                    showEdit={false}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, agreement: null })}
                onConfirmDelete={() => {}}
                itemName={`Agreement #${deleteModal.agreement?.id}` || 'this rental agreement'}
                itemType="rental agreement"
                deleteEndpoint={`/admin/rental-agreements/${deleteModal?.agreement?.id}`}
            />
            <ViewRentalAgreement
                isOpen={isViewModalOpen}
                onClose={() => setIsViewModalOpen(false)}
                agreement={selectedAgreement}
            />
        </>
    );
}
