import { FC, useEffect, useState } from 'react'
import { AddressData } from './types/Types'
import AddressTable from './components/AddressTable'
import AddressForm from './components/AddressForm'
import AddressDeleteModal from './components/AddressDeleteModal'

const Address: FC = () => {
    const [search, setSearch] = useState<string>('')
    const [status, setStatus] = useState<string>('all')
    const [currentPage, setCurrentPage] = useState<number>(1)
    const [selectedAddress, setSelectedAddress] = useState<AddressData | null>(null)
    const [isEditMode, setIsEditMode] = useState(false)
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
    const [addressToDelete, setAddressToDelete] = useState<AddressData | null>(null)

    const handleEdit = (address: AddressData) => {
        setSelectedAddress(address)
        setIsEditMode(true)
    }

    const handleDelete = (address: AddressData) => {
        setAddressToDelete(address)
        setIsDeleteModalOpen(true)
    }

    const handleCancelEdit = () => {
        setSelectedAddress(null)
        setIsEditMode(false)
    }

    const handleFormSuccess = () => {
        setSelectedAddress(null)
        setIsEditMode(false)
    }

    const handleDeleteSuccess = () => {
        setAddressToDelete(null)
    }

    const handleDeleteModalClose = () => {
        setIsDeleteModalOpen(false)
        setAddressToDelete(null)
    }

    useEffect(() => {
        setCurrentPage(1)
    }, [search, status])

    return (
        <div className='flex xl:flex-row flex-col-reverse gap-8 mt-8'>
            <AddressTable
                search={search}
                status={status}
                currentPage={currentPage}
                onSearchChange={setSearch}
                onStatusChange={setStatus}
                onPageChange={setCurrentPage}
                onEdit={handleEdit}
                onDelete={handleDelete}
            />

            <AddressForm
                selectedAddress={selectedAddress}
                isEditMode={isEditMode}
                onCancel={handleCancelEdit}
                onSuccess={handleFormSuccess}
            />

            <AddressDeleteModal
                isOpen={isDeleteModalOpen}
                addressToDelete={addressToDelete}
                onClose={handleDeleteModalClose}
                onSuccess={handleDeleteSuccess}
            />
        </div>
    )
}

export default Address