import Table from '@/components/Table'
import Filters, { type FilterValues, type FieldType } from '@/components/Filters'
import { type FC, useState, useMemo, useCallback } from 'react'
import { useGetUsers } from './hooks/useUsersData'
import type { Customer, CustomerListRow } from '@/pages/customers/types/Types'
import { formatOptionalDate, formatFaNumber } from '@/helpers/func'

const mapCustomerToRow = (customer: Customer): CustomerListRow => {
    const fullName = [customer.firstName, customer.lastName].filter(Boolean).join(' ').trim()
    return {
        id: customer.id,
        fullName: fullName || 'بدون نام',
        phone: customer.phone || '-',
        birthDate: formatOptionalDate(customer.birthDate),
        marriageDate: formatOptionalDate(customer.marriageDate),
        wallet: formatFaNumber(customer.wallet),
        points: formatFaNumber(customer.points),
        status: customer.isActive ? 'فعال' : 'غیرفعال',
    }
}

const CustomersList: FC = () => {
    const { data: usersData, isLoading } = useGetUsers()
    const [filters, setFilters] = useState<FilterValues>({ search: '', status: 'all' })
    const [currentPage, setCurrentPage] = useState(1)
    const limit = 10

    const filterFields = useMemo<FieldType[]>(() => [
        {
            type: 'input',
            name: 'search',
            placeholder: 'نام یا شماره تماس',
        },
        {
            type: 'select',
            name: 'status',
            placeholder: 'انتخاب وضعیت',
            defaultValue: 'all',
            options: [
                { label: 'همه وضعیت‌ها', value: 'all' },
                { label: 'فعال', value: 'active' },
                { label: 'غیرفعال', value: 'inactive' },
            ],
        },
    ], [])

    const customers = useMemo(() => usersData?.data ?? [], [usersData])

    const filteredCustomers = useMemo(() => {
        const searchValue = (filters.search as string || '').toLowerCase().trim()
        const statusFilter = filters.status || 'all'

        return customers.filter((customer) => {
            const fullName = [customer.firstName, customer.lastName].filter(Boolean).join(' ').toLowerCase().trim()
            const matchesSearch =
                searchValue === '' ||
                fullName.includes(searchValue) ||
                (customer.phone || '').includes(searchValue)

            const matchesStatus =
                statusFilter === 'all' ||
                (statusFilter === 'active' && customer.isActive) ||
                (statusFilter === 'inactive' && !customer.isActive)

            return matchesSearch && matchesStatus
        })
    }, [customers, filters])

    const totalPages = Math.max(1, Math.ceil(filteredCustomers.length / limit) || 1)

    const paginatedCustomers = useMemo(() => {
        const startIndex = (currentPage - 1) * limit
        return filteredCustomers.slice(startIndex, startIndex + limit)
    }, [filteredCustomers, currentPage, limit])

    const tableData = useMemo<CustomerListRow[]>(() => paginatedCustomers.map(mapCustomerToRow), [paginatedCustomers])

    const columns = useMemo(() => [
        {
            key: 'fullName',
            title: 'نام و نام خانوادگی',
        },
        {
            key: 'phone',
            title: 'شماره تماس',
        },
        {
            key: 'birthDate',
            title: 'تاریخ تولد',
        },
        {
            key: 'marriageDate',
            title: 'تاریخ ازدواج',
        },
        {
            key: 'wallet',
            title: 'کیف پول (تومان)',
        },
        {
            key: 'points',
            title: 'امتیاز',
        },
        {
            key: 'status',
            title: 'وضعیت',
            render: (item: CustomerListRow) => (
                <span
                    className={`px-3 py-1 rounded-full text-xs ${item.status === 'فعال' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}`}
                >
                    {item.status}
                </span>
            ),
        },
        {
            key: 'details',
            title: 'جزئیات',
        },
    ], [])

    const handlePageChange = (page: number) => {
        setCurrentPage(page)
    }

    const handleFiltersChange = useCallback((newFilters: FilterValues) => {
        setFilters(newFilters)
        setCurrentPage(1)
    }, [])

    return (
        <div className='mt-5'>
            <div className='flex justify-between items-center'>
                <h1 className='text-lg font-light'>لیست مشتریان</h1>
                {/* <Link to={Pages.customers.add}>
                    <Button className='w-fit px-6'>
                        <div className='flex gap-2 items-center'>
                            <Add color='#fff' size={20} />
                            <span>افزودن مشتری</span>
                        </div>
                    </Button>
                </Link> */}
            </div>

            <div className='mt-8'>
                <Filters
                    fields={filterFields}
                    onChange={handleFiltersChange}
                    initialValues={filters}
                    searchField="search"
                />
            </div>

            <Table
                columns={columns}
                data={tableData}
                isloading={isLoading}
                selectable
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default CustomersList