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

export default function Property({ properties, pagination, filters }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [propertyData, setPropertyData] = useState([]);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, property: null });
    const [verifyLoading, setVerifyLoading] = useState({});
    const [statusModal, setStatusModal] = useState({ show: false, property: null, status: "" });
    const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);

    // Handle flash messages from trait (simple format) - prevent duplicates
    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]);

    // Update property data when props change
    useEffect(() => {
        setPropertyData(properties || []);
    }, [properties]);

    // Define columns for property data
    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'title', header: 'Title' },
        { key: 'address', header: 'Address' },
        { key: 'property_type', header: 'Type' },
        { key: 'bedrooms', header: 'Bedrooms' },
        { key: 'bathrooms', header: 'Bathrooms' },
        { key: 'rent_amount', header: 'Rent' },
        { key: 'status', header: 'Status' },
        { key: 'verification_status', header: 'Verification' }
    ];

    // Property type mapping (based on database schema)
    const getPropertyTypeName = (type) => {
        const typeMap = {
            1: 'House',
            2: 'Apartment', 
            3: 'Room',
            4: 'Hostel',
            5: 'Office'
        };
        return typeMap[type] || 'N/A';
    };

    // Status mapping (based on database schema)
    const getStatusName = (status) => {
        const statusMap = {
            1: 'Available',
            2: 'Occupied',
            3: 'Pending',
            4: 'Maintenance'
        };
        return statusMap[status] || 'N/A';
    };

    // Transform data for display
    const transformedData = propertyData.map(property => ({
        ...property,
        is_verified: Boolean(property.is_verified),
        rent_amount: `$${property.monthly_rent?.toLocaleString() || '0'}`,
        property_type: getPropertyTypeName(property.property_type),
        status: getStatusName(property.status),
        status_value: property.status,
        verification_status: property.is_verified
            ? <span className="badge badge-success">Verified</span>
            : <span className="badge badge-warning">Pending</span>,
        address: property.address?.length > 50 ? `${property.address.substring(0, 50)}...` : property.address || 'N/A',
        title: property.title?.length > 30 ? `${property.title.substring(0, 30)}...` : property.title || 'N/A',
    }));

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

    const handleEdit = (row) => {
        fetch(`/admin/properties/${row.id}/edit`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((propertyData) => {
                const formattedData = propertyData;
                setInitialData(formattedData);
                setIsEditModalOpen(true);
            })
            .catch((error) => {
                console.error('Error fetching property details:', error);
                toast.error('Failed to load property details');
            });
    };

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

    const handleVerify = (property) => {
        if (verifyLoading[property.id]) return;

        setVerifyLoading(prev => ({ ...prev, [property.id]: true }));

        router.post(
            `/admin/properties/${property.id}/verify`,
            {},
            {
                onSuccess: () => {
                    toast.success('Property verified successfully');
                    setVerifyLoading(prev => ({ ...prev, [property.id]: false }));
                },
                onError: (errors) => {
                    const errorMessage = errors?.message || 'Failed to verify property';
                    toast.error(errorMessage);
                    setVerifyLoading(prev => ({ ...prev, [property.id]: false }));
                },
                onFinish: () => {
                    setVerifyLoading(prev => ({ ...prev, [property.id]: false }));
                }
            }
        );
    };

    const openStatusModal = (property) => {
        setStatusModal({
            show: true,
            property,
            status: property.status_value ?? 1,
        });
    };

    const closeStatusModal = () => {
        setStatusModal({ show: false, property: null, status: "" });
    };

    const submitStatusUpdate = () => {
        if (!statusModal.property || !statusModal.status) return;
        setIsUpdatingStatus(true);

        router.post(
            `/admin/properties/${statusModal.property.id}/status`,
            { status: statusModal.status },
            {
                onSuccess: () => {
                    closeStatusModal();
                    setIsUpdatingStatus(false);
                },
                onError: (errors) => {
                    const errorMessage = errors?.status?.[0] || errors?.message || 'Failed to update property status';
                    toast.error(errorMessage);
                    setIsUpdatingStatus(false);
                },
                onFinish: () => {
                    setIsUpdatingStatus(false);
                }
            }
        );
    };

    const statusOptions = [
        { value: 1, label: 'Available' },
        { value: 2, label: 'Occupied' },
        { value: 3, label: 'Pending' },
        { value: 4, label: 'Maintenance' },
    ];

    return (
        <>
            <Toaster />
            <div className="row">
                <div className="col-lg-2 mt-4">
                    <Link href="/admin/properties/create" className="btn btn-primary mb-3">
                        Add New Property
                    </Link>
                </div>
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Property Management"
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    noDataText="No properties found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="properties"
                    customActions={(row) => (
                        <>
                            {!row.is_verified && (
                                <li>
                                    <a
                                        href="#"
                                        className="text-success"
                                        onClick={(e) => {
                                            e.preventDefault();
                                            handleVerify(row);
                                        }}
                                        title="Verify Property"
                                        style={{ fontSize: '16px', display: 'inline-block' }}
                                    >
                                        {verifyLoading[row.id] ? (
                                            <i className="fa fa-spinner fa-spin"></i>
                                        ) : (
                                            <i className="fa fa-check"></i>
                                        )}
                                    </a>
                                </li>
                            )}
                            <li>
                                <a
                                    href="#"
                                    className="text-primary"
                                    onClick={(e) => {
                                        e.preventDefault();
                                        openStatusModal(row);
                                    }}
                                    title="Update Status"
                                    style={{ fontSize: '16px', display: 'inline-block' }}
                                >
                                    <i className="fa fa-exchange"></i>
                                </a>
                            </li>
                        </>
                    )}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, property: null })}
                onConfirmDelete={() => {
                    // Let Inertia handle the response and page refresh
                    // The trait will redirect back with success/error messages
                }}
                itemName={deleteModal.property?.title || 'this property'}
                itemType="property"
                deleteEndpoint={`/admin/properties/${deleteModal?.property?.id}`}
            />
            <EditProperty
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                initialData={initialData}
            />

            <Modal
                isOpen={statusModal.show}
                onClose={closeStatusModal}
                title={`Update Status - ${statusModal.property?.title || ''}`}
                primaryButtonText={isUpdatingStatus ? 'Updating...' : 'Update Status'}
                onPrimaryAction={submitStatusUpdate}
                primaryButtonDisabled={isUpdatingStatus}
            >
                <div className="form-group">
                    <label htmlFor="statusSelect">Select Status</label>
                    <select
                        id="statusSelect"
                        className="form-control"
                        value={statusModal.status}
                        onChange={(e) => setStatusModal(prev => ({ ...prev, status: Number(e.target.value) }))}
                    >
                        {statusOptions.map(option => (
                            <option key={option.value} value={option.value}>
                                {option.label}
                            </option>
                        ))}
                    </select>
                </div>
            </Modal>
        </>
    );
}
