import { type FC, useMemo } from 'react'
import { Cell, LabelList, Pie, PieChart, ResponsiveContainer } from 'recharts'
import { useGetFoodSalesPieChart } from '../hooks/useStatsData'
import PageLoading from '@/components/PageLoading'

const COLORS = ['#6B7FED', '#A78BFA', '#FF6B9D', '#FF9A62', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6']

const FoodSalesChart: FC = () => {


    const { data: apiData, isLoading } = useGetFoodSalesPieChart()

    const chartData = useMemo(() => {
        if (!apiData?.data || apiData.data.length === 0) return []

        return apiData.data.map((item, index) => ({
            name: item.foodTitle,
            value: item.quantity,
            color: COLORS[index % COLORS.length],
            revenue: item.revenue,
            percentage: item.percentage
        }))
    }, [apiData?.data])

    const total = useMemo(() => {
        return chartData.reduce((sum, item) => sum + item.value, 0)
    }, [chartData])

    const dataWithPercent = useMemo(() => {
        return chartData.map((item) => ({
            ...item,
            percent: total > 0 ? Math.round((item.value / total) * 100) : 0
        }))
    }, [chartData, total])

    if (isLoading) {
        return (
            <div className='bg-white h-fit rounded-3xl p-6 shadow-sm flex items-center justify-center min-h-[500px]'>
                <PageLoading />
            </div>
        )
    }

    return (
        <div className='bg-white h-fit rounded-3xl p-6 shadow-sm'>
            <h3 className='text-base font-medium mb-6'>میزان فروش کالاها</h3>

            {/* Filters */}
            {/* <div className='flex items-end gap-2 mb-4'>
                <DatePicker
                    label='تاریخ شروع'
                    placeholder='انتخاب تاریخ شروع'
                    onChange={setStartDate}
                />
                <DatePicker
                    label='تاریخ پایان'
                    placeholder='انتخاب تاریخ پایان'
                    onChange={setEndDate}
                />
            </div> */}

            {/* Tabs */}
            {/* <div className='flex items-center gap-2 mb-6'>
                <button
                    onClick={() => setSelectedTab('yearly')}
                    className={`px-4 py-1.5 rounded-full text-xs transition-all border ${selectedTab === 'yearly'
                        ? 'bg-black text-white border-black'
                        : 'bg-white text-gray-600 border-gray-200'
                        }`}
                >
                    سالانه
                </button>
                <button
                    onClick={() => setSelectedTab('monthly')}
                    className={`px-4 py-1.5 rounded-full text-xs transition-all border ${selectedTab === 'monthly'
                        ? 'bg-black text-white border-black'
                        : 'bg-white text-gray-600 border-gray-200'
                        }`}
                >
                    ماهانه
                </button>
                <button
                    onClick={() => setSelectedTab('daily')}
                    className={`px-4 py-1.5 rounded-full text-xs transition-all border ${selectedTab === 'daily'
                        ? 'bg-black text-white border-black'
                        : 'bg-white text-gray-600 border-gray-200'
                        }`}
                >
                    روزانه
                </button>
            </div> */}

            {dataWithPercent.length === 0 ? (
                <div className='flex items-center justify-center min-h-[400px] text-gray-500'>
                    داده‌ای برای نمایش وجود ندارد
                </div>
            ) : (
                <>
                    <div className='flex items-center justify-center mb-6'>
                        <ResponsiveContainer
                            width='100%'
                            height={280}
                        >
                            <PieChart>
                                <Pie
                                    data={dataWithPercent}
                                    cx='50%'
                                    cy='50%'
                                    innerRadius={70}
                                    outerRadius={110}
                                    paddingAngle={3}
                                    dataKey='value'
                                >
                                    {dataWithPercent.map((entry, index) => (
                                        <Cell
                                            key={`cell-${index}`}
                                            fill={entry.color}
                                        />
                                    ))}
                                    <LabelList
                                        dataKey='percent'
                                        position='outside'
                                        content={(props: unknown) => {
                                            const labelProps = props as {
                                                x?: number | string
                                                y?: number | string
                                                value?: number | string
                                            }
                                            if (
                                                labelProps.x === undefined ||
                                                labelProps.y === undefined ||
                                                labelProps.value === undefined
                                            ) {
                                                return null
                                            }
                                            const x =
                                                typeof labelProps.x === 'number'
                                                    ? labelProps.x
                                                    : parseFloat(
                                                        String(labelProps.x)
                                                    ) || 0
                                            const y =
                                                typeof labelProps.y === 'number'
                                                    ? labelProps.y
                                                    : parseFloat(
                                                        String(labelProps.y)
                                                    ) || 0
                                            return (
                                                <text
                                                    x={x}
                                                    y={y}
                                                    textAnchor='middle'
                                                    fontSize='14'
                                                    fontWeight={500}
                                                    fill='#1F2937'
                                                >
                                                    {labelProps.value}%
                                                </text>
                                            )
                                        }}
                                    />
                                </Pie>
                            </PieChart>
                        </ResponsiveContainer>
                    </div>

                    <div className='flex items-center gap-6 flex-wrap'>
                        {dataWithPercent.map((item, index) => (
                            <div
                                key={index}
                                className='flex items-center gap-2'
                            >
                                <div
                                    className='w-3 h-3 rounded-full flex-shrink-0'
                                    style={{ backgroundColor: item.color }}
                                />
                                <span className='text-sm text-gray-700'>
                                    {item.name}
                                </span>
                            </div>
                        ))}
                    </div>
                </>
            )}
        </div>
    )
}

export default FoodSalesChart

