import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../services/api';
import BarHorizontal, { type BarHorizontalRow } from '@/components/graphs/BarHorizontal';
import BarVertical from '@/components/graphs/BarVertical';
import TypographyAnimated from '@/components/ui/TypographyAnimated';
import { useLocale } from '@/context/LocaleContext';
import { Box, Typography } from '@mui/material';
import GaugeScore from '@/components/graphs/GaugeScore';
import AppCard from '@/components/ui/Card';
import AppAlert from '@/components/ui/Alert';

const COMPLIANCE_BY_INDICATOR = '/api/complianceByIndicator';
const COMPLIANCE_BY_AGENT = '/api/complianceByAgent';
const COMPLIANCE_BY_PERFORMANCE_BY_AGENT = '/api/complianceByPerformanceByAgent';

/** Respuesta de ComplianceController::getPerformanceByAgent */
type PerformanceByAgent = {
    mejorScore?: number | null;
    mejorAgent?: string;
    mejor_agent_id?: number | null;
    peorScore?: number | null;
    peorAgent?: string;
    peor_agent_id?: number | null;
};

/** Respuesta alineada con ComplianceController::getComplianceByIndicator */
type ComplianceSeries = { name: string; data: number[] };
type ComplianceApiResponse = {
    chart: { type: string };
    series: ComplianceSeries[];
    xaxis: {
        categories: string[];
        labels?: { style?: Record<string, unknown> };
    };
};

function buildRows(data: ComplianceApiResponse): BarHorizontalRow[] {
    const categories = data.xaxis.categories;
    const noCumpleSeries = data.series.find((s) => s.name === 'No Cumple')?.data ?? [];
    const cumpleSeries = data.series.find((s) => s.name === 'Cumple')?.data ?? [];
    return categories.map((name, i) => ({
        name,
        noCumple: Number(noCumpleSeries[i] ?? 0),
        cumple: Number(cumpleSeries[i] ?? 0),
    }));
}

export default function Compliance() {
    const { t } = useLocale();
    const [rowsByIndicator, setRowsByIndicator] = useState<BarHorizontalRow[]>([]);
    const [rowsByAgent, setRowsByAgent] = useState<BarHorizontalRow[]>([]);
    const [performanceByAgent, setPerformanceByAgent] = useState<PerformanceByAgent>({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        let cancelled = false;
        (async () => {
            setLoading(true);
            setError(null);
            try {
                const [byInd, byAgent, byPerformanceByAgent] = await Promise.allSettled([
                    api.get<ComplianceApiResponse>(COMPLIANCE_BY_INDICATOR),
                    api.get<ComplianceApiResponse>(COMPLIANCE_BY_AGENT),
                    api.get<ComplianceApiResponse>(COMPLIANCE_BY_PERFORMANCE_BY_AGENT),
                ]);
                if (cancelled) {
                    return;
                }
                if (byInd.status === 'fulfilled') {
                    setRowsByIndicator(buildRows(byInd.value.data));
                } else {
                    setRowsByIndicator([]);
                }
                if (byAgent.status === 'fulfilled') {
                    setRowsByAgent(buildRows(byAgent.value.data));
                } else {
                    setRowsByAgent([]);
                }
                if (byInd.status === 'rejected' && byAgent.status === 'rejected') {
                    setError('No se pudo cargar el cumplimiento.');
                } else if (byInd.status === 'rejected' || byAgent.status === 'rejected') {
                    setError('Algunos datos no se pudieron cargar.');
                }
                if (byPerformanceByAgent.status === 'fulfilled') {
                    setPerformanceByAgent(byPerformanceByAgent.value.data as PerformanceByAgent);
                } else {
                    setPerformanceByAgent({});
                }
            } finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        })();
        return () => {
            cancelled = true;
        };
    }, []);

    const hasIndicator = rowsByIndicator.length > 0;
    const hasAgent = rowsByAgent.length > 0;
    const hasBoth = hasIndicator && hasAgent;

    /** Misma altura (px) para ambos gráficos, en función del máximo de categorías entre las dos series. */
    const sharedChartHeight = useMemo(() => {
        const n = Math.max(rowsByIndicator.length, rowsByAgent.length);
        return Math.max(360, n * 44);
    }, [rowsByIndicator.length, rowsByAgent.length]);

    return (
        <div className="container-fluid w-full space-y-6 py-4">
                    <TypographyAnimated
                        variant="subtitle2"
                        prefix={t('compliance', 'top_heading_prefix')}
                        rotatingWords={t('compliance', 'top_heading_rotating')
                            .split('|')
                            .map((s) => s.trim())
                            .filter(Boolean)}
                        sx={{
                            color: 'text.primary',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '0.18em',
                            fontSize: '1.3rem',
                        }}
                    />

            {loading && <p className="text-sm text-zinc-600 dark:text-zinc-400">Cargando…</p>}
            {!loading && error && !hasIndicator && !hasAgent && (
                <p className="text-sm text-red-600">{error}</p>
            )}

            {!loading && rowsByIndicator.length === 0 && rowsByAgent.length === 0 && !error && (
                <p className="text-sm text-zinc-600 dark:text-zinc-400">{t('compliance', 'no_data_to_show')}</p>
            )}

            {!loading && (rowsByIndicator.length > 0 || rowsByAgent.length > 0) && (
                <>
                    <Box
                        sx={{
                            display: 'flex',
                            flexDirection: 'row',
                            flexWrap: 'nowrap',
                            alignItems: 'stretch',
                            gap: 2,
                            mb: 2,
                            mt: 2,
                            justifyContent: 'center',
                            width: '100%',
                            overflowX: 'auto',
                        }}
                    >
                        <Box
                            sx={{
                                width: '30%',
                                minWidth: { xs: 220, sm: 260 },
                                maxWidth: '30%',
                                boxSizing: 'border-box',
                                flexShrink: 0,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                border: 1,
                                borderColor: 'divider',
                                borderRadius: 2,
                                px: 1.5,
                                py: 2,
                            }}
                        >
                            {error ? (
                                <Typography color="error" variant="body2" sx={{ textAlign: 'center' }}>
                                    {error}
                                </Typography>
                            ) : (
                                <GaugeScore
                                    value={performanceByAgent.mejorScore}
                                    aria-label={t('compliance', 'best_performance_by_agent')}
                                    activeColor="#00D8FF"
                                    inactiveColor="#FF0000"
                                    footer={
                                        <>
                                            <Typography
                                                variant="caption"
                                                sx={{
                                                    display: 'block',
                                                    fontWeight: 700,
                                                    textTransform: 'uppercase',
                                                    letterSpacing: '0.06em',
                                                    color: 'text.secondary',
                                                }}
                                            >
                                                {t('compliance', 'best_performance_by_agent').toUpperCase()}
                                            </Typography>
                                            <Typography variant="body2" sx={{ mt: 0.5,fontSize: '1.5rem' }}>
                                                {performanceByAgent.mejorAgent}
                                            </Typography>
                                            {performanceByAgent.mejor_agent_id != null ? (
                                                <Link
                                                    to={`/compliance-detail?agent_id=${performanceByAgent.mejor_agent_id}`}
                                                    className="mt-1 inline-block text-sm font-semibold underline underline-offset-2"
                                                >
                                                    {t('compliance', 'link_agent_detail')}
                                                </Link>
                                            ) : null}
                                        </>
                                    }
                                />
                            )}
                        </Box>
                        <Box
                            sx={{
                                width: '30%',
                                minWidth: { xs: 220, sm: 260 },
                                maxWidth: '30%',
                                boxSizing: 'border-box',
                                flexShrink: 0,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                border: 1,
                                borderColor: 'divider',
                                borderRadius: 2,
                                px: 1.5,
                                py: 2,
                            }}
                        >
                            {error ? (
                                <Typography color="error" variant="body2" sx={{ textAlign: 'center' }}>
                                    {error}
                                </Typography>
                            ) : (
                                <GaugeScore
                                    value={performanceByAgent.peorScore}
                                    aria-label={t('compliance', 'worst_performance_by_agent')}
                                    activeColor="#00D8FF"
                                    inactiveColor="#FF0000"
                                    footer={
                                        <>
                                            <Typography
                                                variant="caption"
                                                sx={{
                                                    display: 'block',
                                                    fontWeight: 700,
                                                    textTransform: 'uppercase',
                                                    letterSpacing: '0.06em',
                                                    color: 'text.secondary',
                                                }}
                                            >
                                                {t('compliance', 'worst_performance_by_agent').toUpperCase()}
                                            </Typography>
                                            <Typography variant="body2" sx={{ mt: 0.5,fontSize: '1.5rem'  }}>
                                                {performanceByAgent.peorAgent}
                                            </Typography>
                                            {performanceByAgent.peor_agent_id != null ? (
                                                <Link
                                                    to={`/compliance-detail?agent_id=${performanceByAgent.peor_agent_id}`}
                                                    className="mt-1 inline-block text-sm font-semibold underline underline-offset-2"
                                                >
                                                    {t('compliance', 'link_agent_detail')}
                                                </Link>
                                            ) : null}
                                        </>
                                    }
                                />
                            )}
                        </Box>
                    </Box>
                    <div className="grid w-full grid-cols-1 gap-4 lg:grid-cols-2">
                    {hasIndicator && (
                        <div className={hasBoth ? 'min-w-0' : 'min-w-0 lg:col-span-2'}>
                            <AppCard>
                                <Typography variant="h6" sx={{ mb: 1 }}>
                                    {t('compliance', 'compliance_by_indicator')}
                                </Typography>
                                <BarHorizontal
                                    className="w-full min-w-0"
                                    data={rowsByIndicator}
                                    height={sharedChartHeight}
                                    aria-label="Cumplimiento por indicador"
                                />
                            </AppCard>
                        </div>
                    )}
                    {hasAgent && (
                        <div className={hasBoth ? 'min-w-0' : 'min-w-0 lg:col-span-2'}>
                            <AppCard>
                                <Typography variant="h6" sx={{ mb: 1 }}>
                                    {t('compliance', 'compliance_by_agent')}
                                </Typography>
                                <BarVertical
                                    className="w-full min-w-0"
                                    data={rowsByAgent}
                                    height={sharedChartHeight}
                                    aria-label="Cumplimiento por agente"
                                />
                            </AppCard>
                        </div>
                    )}
                </div>
                </>
            )}
            <a
                href="https://recharts.github.io/"
                target="_blank"
                rel="noopener noreferrer"
                className="fixed bottom-4 right-4 z-10 text-xs text-zinc-500 no-underline transition-colors hover:text-zinc-700 hover:underline dark:text-zinc-400 dark:hover:text-zinc-200"
            >
                Powered by Recharts
            </a>
        </div>
    );
}
