'use client';

import { useEffect, useState, useCallback, ChangeEvent, useMemo } from 'react';
import Container from '@mui/material/Container';
import { paths } from '@/routes/paths';
import { useSettingsContext } from '@/shared/components/settings';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { TextField, ToggleButtonGroup, Card, Stack, Divider, Grid, CardHeader, CardContent, ToggleButton, Select, MenuItem, InputLabel, FormControl, SelectChangeEvent } from '@mui/material';
import Iconify from '@/shared/components/iconify/iconify';
import InputAdornment from '@mui/material/InputAdornment'; 
import { useTheme } from '@mui/material/styles';
import Scrollbar from '@/shared/components/scrollbar';
import InvoiceAnalytic from '../invoice-analytic';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import ChartPie from '@/shared/sections/chart-view/chart-pie';
import ChartColumnStacked from '@/shared/sections/chart-view/chart-column-stacked';
import ChartDonut from '@/shared/sections/chart-view/chart-donut';
import ChartLineArea from '@/shared/sections/chart-view/chart-line-area';
import { getInvoiceAnalyticsSummary, getInvoiceDistribution, getTotalRevenueByPaymentMode, getInvoiceDistributionByStatus, getClientInvoiceDistribution, InvoiceAnalyticsSummary, ChartLineAreaData, ChartDonutData, ChartPieData, ClientInvoiceDistribution } from '@/shared/api/invoice';
import { getAgencyById, getUserCurrency } from '@/shared/api/user';
import { fCurrency, fShortenNumber } from '@/utils/format-number';
import InvoiceLayout from './invoice-layout';

export default function InvoiceAnalyticsView() {
    const settings = useSettingsContext();
    const theme = useTheme();
    const [view, setView] = useState('analytic');
    const [analyticsData, setAnalyticsData] = useState<InvoiceAnalyticsSummary | null>(null);
    const [distributionData, setDistributionData] = useState<ChartLineAreaData | null>(null);
    const [paymentModeData, setPaymentModeData] = useState<ChartDonutData | null>(null);
    const [statusDistributionData, setStatusDistributionData] = useState<ChartPieData | null>(null);
    const [clientDistributionData, setClientDistributionData] = useState<ClientInvoiceDistribution | null>(null);
    const [selectedDate, setSelectedDate] = useState<Date>(new Date());
    const [selectedValue, setSelectedValue] = useState<string>('');
    const [searchValueGrp, setSearchValueGrp] = useState('');
    const [currency, setCurrency] = useState<string>('USD');
    const [startDate, setStartDate] = useState(() => {
        const date = new Date();
        date.setMonth(date.getMonth() - 12); 
        date.setDate(1); 
        return date;
    });
    
    const [endDate, setEndDate] = useState(() => {
        const date = new Date();
        date.setDate(date.getDate()); 
        return date;
    });

    const fetchCurrency = useCallback(async () => {
        try {
            const agencyId = localStorage.getItem('selectedAgency');
            if (!agencyId) {
                throw new Error('Agency ID not found');
            }

            const agencyData = await getAgencyById(agencyId);
            const agencyCurrency = agencyData.currency || 'USD'; 
            setCurrency(agencyCurrency);
        } catch (error) {
            console.error('Error fetching agency currency:', error);
            setCurrency('USD'); 
        }
    }, []);

    useEffect(() => {
        fetchCurrency();
    }, [fetchCurrency]);

    const fetchData = useCallback(async () => {
        try {
            const summary = await getInvoiceAnalyticsSummary(currency);
            setAnalyticsData(summary);

            const start = startDate.toISOString().split('T')[0];
            const end = endDate.toISOString().split('T')[0];
            const distribution = await getInvoiceDistribution(start, end, currency);
            setDistributionData(distribution);

            const paymentMode = await getTotalRevenueByPaymentMode(currency);
            setPaymentModeData(paymentMode);

            const statusDistribution = await getInvoiceDistributionByStatus(currency);
            setStatusDistributionData(statusDistribution);

            const clientDistribution = await getClientInvoiceDistribution(currency);
            setClientDistributionData(clientDistribution);
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    }, [selectedDate, currency, startDate, endDate]);

    useEffect(() => {
        if (currency) {
            fetchData();
        }
    }, [fetchData, currency]);

    const handleChangeView = useCallback(
        (event: React.MouseEvent<HTMLElement>, newView: string | null) => {
          if (newView !== null) {
            setView(newView);
          }
        },
        []
    );

    const handleDateChange = (newValue: Date | null) => {
        if (newValue instanceof Date) {
            setSelectedDate(newValue);
        }
    };

    const handleChange = (event: SelectChangeEvent<string>) => { 
        setSelectedValue(event.target.value);
    };

    const handleSearchChangeGrp = (event: ChangeEvent<HTMLInputElement>) => {
        setSearchValueGrp(event.target.value);
    };

    const formattedDistributionData = useMemo(() => {
        if (!distributionData) return null;
        return {
            labels: distributionData.labels,
            series: distributionData.series.map((series: any) => ({
                ...series,
                type: 'area',
                fill: 'gradient',
            })),
            options: {
                tooltip: {
                    y: {
                        formatter: (value: number) => `${fCurrency(value, currency)} ${currency}`
                    }
                }
            }
        };
    }, [distributionData, currency]);

    return (
        <InvoiceLayout>
            <LocalizationProvider dateAdapter={AdapterDateFns}>
                <Container maxWidth={settings.themeStretch ? false : 'lg'}>
                    <CustomBreadcrumbs
                        heading={`Analytics (${currency})`}
                        links={[
                            { name: 'Dashboard', href: paths.dashboard.root },
                            { name: 'Invoice', href: paths.dashboard.invoice.root },
                            { name: 'Analytics' },
                        ]}
                        sx={{ mb: { xs: 3, md: 5 } }}
                    />

                    <Stack
                        spacing={1}
                        direction={{ xs: 'column', md: 'row' }}
                        alignItems={{ xs: 'flex-end', md: 'center' }}
                        marginBottom="20px"
                        sx={{ width: 1 }}
                    >
                        <Stack spacing={1} direction="row" alignItems="center" justifyContent="flex-end" flexGrow={1}>
                            <ToggleButtonGroup size="small" value={view} exclusive onChange={handleChangeView}>
                                <ToggleButton value="list">
                                    <a href={paths.dashboard.invoice.root}>
                                        <Iconify icon="solar:list-bold" />
                                    </a>  
                                </ToggleButton>
                                <ToggleButton value="grid">
                                    <a href={paths.dashboard.invoice.grid}>
                                        <Iconify icon="mingcute:dot-grid-fill" />
                                    </a>    
                                </ToggleButton>
                                <ToggleButton value="analytic">
                                    <a href={paths.dashboard.invoice.analytics}>
                                        <Iconify icon="carbon:analytics" />
                                    </a>
                                </ToggleButton>
                            </ToggleButtonGroup>
                        </Stack>    
                    </Stack>

                    <Stack spacing={3}>
                        {analyticsData && (
                            <Card>
                                <Scrollbar>
                                    <Stack
                                        direction="row"
                                        divider={<Divider orientation="vertical" flexItem sx={{ borderStyle: 'dashed' }} />}
                                        sx={{ py: 2 }}
                                    >
                                        <InvoiceAnalytic
                                            title="Total"
                                            total={analyticsData.totalInvoices}
                                            percent={100}
                                            price={analyticsData.totalAmount}
                                            icon="solar:bill-list-bold-duotone"
                                            color={theme.palette.text.secondary}
                                            currency={currency}
                                        />
                                        <InvoiceAnalytic
                                            title="Paid"
                                            total={analyticsData.paid.count}
                                            percent={(analyticsData.paid.count / analyticsData.totalInvoices) * 100}
                                            price={analyticsData.paid.total}
                                            icon="solar:file-check-bold-duotone"
                                            color={theme.palette.success.main}
                                            currency={currency}
                                        />
                                        <InvoiceAnalytic
                                            title="Pending"
                                            total={analyticsData.pending.count}
                                            percent={(analyticsData.pending.count / analyticsData.totalInvoices) * 100}
                                            price={analyticsData.pending.total}
                                            icon="solar:sort-by-time-bold-duotone"
                                            color={theme.palette.warning.main}
                                            currency={currency}
                                        />
                                        <InvoiceAnalytic
                                            title="Overdue"
                                            total={analyticsData.overdue.count}
                                            percent={(analyticsData.overdue.count / analyticsData.totalInvoices) * 100}
                                            price={analyticsData.overdue.total}
                                            icon="solar:bell-bing-bold-duotone"
                                            color={theme.palette.error.main}
                                            currency={currency}
                                        />
                                        <InvoiceAnalytic
                                            title="Draft"
                                            total={analyticsData.draft.count}
                                            percent={(analyticsData.draft.count / analyticsData.totalInvoices) * 100}
                                            price={analyticsData.draft.total}
                                            icon="solar:file-corrupted-bold-duotone"
                                            color={theme.palette.info.main}
                                            currency={currency}
                                        />
                                    </Stack>
                                </Scrollbar>
                            </Card>
                        )}

                        {formattedDistributionData && (
                            <Card>
                                <CardHeader 
                                    title={`Distribution of invoices gains by month (${currency})`}
                                    titleTypographyProps={{ align: 'center' }} 
                                />
                                <CardContent>
                                    <ChartLineArea
                                        title=""
                                        subheader=""
                                        chart={formattedDistributionData}
                                    />
                                </CardContent>
                            </Card>
                        )}

                        <Grid container spacing={3}>
                            {paymentModeData && (
                                <Grid item xs={12} md={6}>
                                    <Card sx={{ height: '100%' }}>
                                        <CardHeader 
                                            title={`Total income by payment mode (${currency})`}
                                            titleTypographyProps={{ align: 'center' }} 
                                        />    
                                        <CardContent>
                                            <ChartDonut
                                                title=""
                                                chart={{
                                                    series: paymentModeData.series,
                                                    options: {
                                                        tooltip: {
                                                            y: {
                                                                formatter: (value: number) => fCurrency(value, currency)
                                                            }
                                                        },
                                                        legend: {
                                                            formatter: (label: string, opts: any) => {
                                                                const value = opts.w.globals.series[opts.seriesIndex];
                                                                const cleanLabel = label.replace(/\s*[A-Z]{3}$/, '').replace(/^(CA\$|€|\$|£|¥)/, '').trim();
                                                                return `${cleanLabel}: ${fCurrency(value, currency)}`;
                                                            }
                                                        }
                                                    }
                                                }}
                                            />
                                        </CardContent>  
                                    </Card>       
                                </Grid>
                            )}

                            {statusDistributionData && (
                                <Grid item xs={12} md={6}>
                                    <Card sx={{ height: '100%' }}>
                                        <CardHeader 
                                            title="Invoice distribution by status"
                                            titleTypographyProps={{ align: 'center' }} 
                                        />
                                        <CardContent>
                                            <ChartPie 
                                                title=""
                                                chart={{
                                                    series: statusDistributionData.series,
                                                    options: {
                                                        tooltip: {
                                                            y: {
                                                                formatter: (value: number) => `${fShortenNumber(value)} (${value.toFixed(2)}%)`
                                                            }
                                                        }
                                                    }
                                                }}     
                                            />
                                        </CardContent>
                                    </Card>     
                                </Grid>
                            )}
                        </Grid>

                        {clientDistributionData && (
                            <Card>
                                <CardHeader 
                                    title={`Distribution of invoice revenues by customer (${currency})`}
                                    titleTypographyProps={{ align: 'center' }} 
                                />
                                <Stack
                                    spacing={1}
                                    alignItems={{ xs: 'flex-end', md: 'center' }}
                                    direction={{
                                        xs: 'column',
                                        md: 'row',
                                    }}
                                    sx={{
                                        px: 2.5,
                                        py: 1,
                                    }}
                                >            
                                    <TextField
                                        placeholder="Search..."
                                        value={searchValueGrp}
                                        onChange={handleSearchChangeGrp}
                                        InputProps={{
                                            startAdornment: (
                                                <InputAdornment position="start">
                                                    <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                                                </InputAdornment>
                                            ),
                                        }}
                                    />
                                </Stack>
                                <CardContent>
                                    <ChartColumnStacked
                                        series={clientDistributionData.series}
                                        axis={clientDistributionData.clients}
                                        searchValue={searchValueGrp}
                                        color={[]}
                                        customOptions={{
                                            tooltip: {
                                                y: {
                                                    formatter: (value: number) => `${fCurrency(value, currency)} ${currency}`
                                                }
                                            }
                                        }}
                                    />
                                </CardContent>
                            </Card>
                        )}
                    </Stack>
                </Container>
            </LocalizationProvider>
        </InvoiceLayout>
    );
}