import { ApexAreaChartCard } from '../components/charts/ApexAreaChartCard';
import { ApexBarChartCard } from '../components/charts/ApexBarChartCard';
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSalesGrowthReport, useUserRegistrationGrowthReport, useSalesByCategoryReport } from './reports/sales-statistics/core/_hooks';
import { useOrders } from './orders/core/_hooks';
import { StatusBadge } from '../components/ui/StatusBadge';
import { formatCurrency, formatDate } from '../utils/formatters';

import { PieChart } from '../components/charts/PieChart';
import { Table } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { PageContainer, PageTitle, CardTitle } from '../components/ui/Typography';
import { ChartData, TableColumn } from '../types';

export const Dashboard = () => {
    const navigate = useNavigate();
    const { data: salesGrowthReport } = useSalesGrowthReport({ group_by: 'month' });
    const { data: registrationGrowthReport } = useUserRegistrationGrowthReport({ group_by: 'month' });
    const { data: salesByCategoryReport } = useSalesByCategoryReport();
    const recentOrdersFilters = useMemo(() => ({
        page: 1,
        limit: 5,
        status: 'pending' as const,
    }), []);
    const { data: recentOrders, isLoading: isOrdersLoading } = useOrders(recentOrdersFilters);

    const monthlySalesData: ChartData[] = useMemo(() => {
        return (salesGrowthReport?.sales || []).map((item) => ({
            name: item.month_name || `${item.year}/${item.month}`,
            value: item.total_sales,
        }));
    }, [salesGrowthReport]);

    const registrationGrowthData: ChartData[] = useMemo(() => {
        return (registrationGrowthReport?.registrations || []).map((item) => ({
            name: item.month_name || `${item.year}/${item.month}`,
            value: item.total_users,
        }));
    }, [registrationGrowthReport]);

    const salesByCategoryData: ChartData[] = useMemo(() => {
        return (salesByCategoryReport?.categories || []).map((item) => ({
            name: item.category_name,
            value: item.percentage,
        }));
    }, [salesByCategoryReport]);

    const orderColumns: TableColumn[] = [
        {
            key: 'order_number',
            label: 'شماره سفارش',
            render: (value: string) => `#${value}`,
        },
        {
            key: 'customer',
            label: 'مشتری',
            render: (_value, row: any) => {
                const customer = row.user || row.customer;
                const name = `${customer?.first_name || ''} ${customer?.last_name || ''}`.trim();
                return name || 'نامشخص';
            },
        },
        {
            key: 'final_total',
            label: 'مبلغ',
            render: (_value, row: any) => formatCurrency(row.final_total || row.total_amount || 0),
        },
        {
            key: 'status',
            label: 'وضعیت',
            render: (value: any) => <StatusBadge status={value} type="order" />,
        },
        {
            key: 'created_at',
            label: 'تاریخ',
            render: (value: string) => formatDate(value),
        },
    ];

    const ordersTableData = (recentOrders?.orders || []).map((item) => item.order ?? item);

    return (
        <PageContainer>
            {/* Header with mobile-responsive layout */}
            <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                <PageTitle>داشبورد</PageTitle>
            </div>

            {/* Charts - Better mobile layout */}
            <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 sm:gap-6">
                <div className="min-w-0">
                    <ApexBarChartCard
                        data={monthlySalesData}
                        title="فروش ماهانه"
                        color="#3b82f6"
                    />
                </div>
                <div className="min-w-0">
                    <ApexAreaChartCard
                        data={registrationGrowthData}
                        title="روند رشد ثبت‌نام کاربران"
                        color="#10b981"
                    />
                </div>
            </div>

            {/* Table and Pie Chart - Mobile responsive */}
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 sm:gap-6">
                <div className="xl:col-span-2 min-w-0">
                    <div className="card p-3 sm:p-4 lg:p-6">
                        <CardTitle className="mb-3 sm:mb-4">
                            آخرین سفارشات در انتظار
                        </CardTitle>
                        <div className="overflow-x-auto">
                            <Table columns={orderColumns} data={ordersTableData} loading={isOrdersLoading} />
                        </div>
                        <div className="mt-4 flex justify-end">
                            <Button variant="secondary" onClick={() => navigate('/orders')}>
                                مشاهده همه
                            </Button>
                        </div>
                    </div>
                </div>
                <div className="min-w-0">
                    <PieChart
                        data={salesByCategoryData}
                        title="توزیع فروش بر اساس دسته‌بندی"
                        colors={['#3b82f6', '#10b981', '#f59e0b']}
                    />
                </div>
            </div>
        </PageContainer>
    );
}; 