import React, { useState } from 'react';
import {
  Activity,
  Clock,
  TrendingUp,
  Target,
  AlertCircle,
  Download,
  Calendar,
  BarChart3,
  Zap,
  DollarSign,
  Package,
  AlertOctagon,
} from 'lucide-react';
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  LineChart,
  Line,
  RadarChart,
  Radar,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
} from 'recharts';
import { Badge, Card } from '../../../../components/ui';
import { AnalyticsPageLayout, AnalyticsCard } from '../../../../components/analytics';
import { useSubscription } from '../../../../api/hooks/subscription';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';
import {
  useCycleTimeMetrics,
  useProcessEfficiencyScore,
  useResourceUtilization,
  useCostRevenueRatio,
  useQualityImpactIndex,
  useCriticalBottlenecks,
  useDepartmentPerformance,
  usePerformanceAlerts,
} from '../../../../api/hooks/performance';
import { TimePeriod } from '../../../../api/types/performance';

// Formatters for StatsGrid - Note: currency uses dynamic symbol from hook in the component
const formatters = {
  number: (value: number) => value.toFixed(0),
  percentage: (value: number) => `${value.toFixed(1)}%`,
  hours: (value: number) => `${value.toFixed(1)}h`,
  currency: (value: number, currencySymbol: string = '€') => `${currencySymbol}${value.toLocaleString('es-ES', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`,
};

const PerformanceAnalyticsPage: React.FC = () => {
  const { canAccessAnalytics, subscriptionInfo } = useSubscription();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const { currencySymbol } = useTenantCurrency();

  const [selectedPeriod, setSelectedPeriod] = useState<TimePeriod>('week');
  const [activeTab, setActiveTab] = useState('overview');

  // Fetch all cross-functional performance data
  const { data: cycleTime, isLoading: cycleTimeLoading } = useCycleTimeMetrics(tenantId, selectedPeriod);
  const { data: processScore, isLoading: processScoreLoading } = useProcessEfficiencyScore(tenantId, selectedPeriod);
  const { data: resourceUtil, isLoading: resourceUtilLoading } = useResourceUtilization(tenantId, selectedPeriod);
  const { data: costRevenue, isLoading: costRevenueLoading } = useCostRevenueRatio(tenantId, selectedPeriod);
  const { data: qualityIndex, isLoading: qualityIndexLoading } = useQualityImpactIndex(tenantId, selectedPeriod);
  const { data: bottlenecks, isLoading: bottlenecksLoading } = useCriticalBottlenecks(tenantId, selectedPeriod);
  const { data: departments, isLoading: departmentsLoading } = useDepartmentPerformance(tenantId, selectedPeriod);
  const { data: alerts, isLoading: alertsLoading } = usePerformanceAlerts(tenantId);

  // Period options
  const timeframes: { value: TimePeriod; label: string }[] = [
    { value: 'day', label: 'Hoy' },
    { value: 'week', label: 'Esta Semana' },
    { value: 'month', label: 'Este Mes' },
    { value: 'quarter', label: 'Trimestre' },
    { value: 'year', label: 'Año' },
  ];

  // Tab configuration
  const tabs = [
    { id: 'overview', label: 'Vista General' },
    { id: 'efficiency', label: 'Eficiencia Operativa' },
    { id: 'quality', label: 'Impacto de Calidad' },
    { id: 'optimization', label: 'Optimización' },
  ];

  // Combined loading state
  const isLoading =
    cycleTimeLoading ||
    processScoreLoading ||
    resourceUtilLoading ||
    costRevenueLoading ||
    qualityIndexLoading ||
    bottlenecksLoading ||
    departmentsLoading ||
    alertsLoading;

  // Helper functions
  const getTrendIcon = (trend: 'up' | 'down' | 'stable') => {
    if (trend === 'up') {
      return <TrendingUp className="w-4 h-4 text-[var(--color-success)]" />;
    } else if (trend === 'down') {
      return <TrendingUp className="w-4 h-4 text-[var(--color-error)] transform rotate-180" />;
    }
    return <Activity className="w-4 h-4 text-gray-500" />;
  };

  const getAlertIcon = (type: 'warning' | 'critical' | 'info') => {
    switch (type) {
      case 'critical':
        return <AlertCircle className="w-5 h-5 text-[var(--color-error)]" />;
      case 'warning':
        return <AlertCircle className="w-5 h-5 text-yellow-600" />;
      default:
        return <Activity className="w-5 h-5 text-[var(--color-info)]" />;
    }
  };

  const getAlertColor = (type: 'warning' | 'critical' | 'info') => {
    switch (type) {
      case 'critical':
        return 'bg-red-50 border-red-200';
      case 'warning':
        return 'bg-yellow-50 border-yellow-200';
      default:
        return 'bg-[var(--color-info)]/5 border-[var(--color-info)]/20';
    }
  };

  // Prepare StatsGrid data (6 cross-functional metrics) - NO MEMOIZATION to avoid loops
  const statsData = [
    {
      title: 'Tiempo de Ciclo',
      value: cycleTime?.average_cycle_time || 0,
      icon: Clock,
      formatter: formatters.hours,
    },
    {
      title: 'Eficiencia de Procesos',
      value: processScore?.overall_score || 0,
      icon: Zap,
      formatter: formatters.percentage,
    },
    {
      title: 'Utilización de Recursos',
      value: resourceUtil?.overall_utilization || 0,
      icon: Package,
      formatter: formatters.percentage,
    },
    {
      title: 'Ratio Costo-Ingreso',
      value: costRevenue?.cost_revenue_ratio || 0,
      icon: DollarSign,
      formatter: formatters.percentage,
    },
    {
      title: 'Índice de Calidad',
      value: qualityIndex?.overall_quality_index || 0,
      icon: Target,
      formatter: formatters.percentage,
    },
    {
      title: 'Cuellos de Botella Críticos',
      value: bottlenecks?.critical_count || 0,
      icon: AlertOctagon,
      formatter: formatters.number,
    },
  ];

  return (
    <AnalyticsPageLayout
      title="Análisis de Rendimiento"
      description="Monitorea métricas transversales que muestran cómo los departamentos trabajan juntos"
      subscriptionLoading={subscriptionInfo.loading}
      hasAccess={canAccessAnalytics('advanced')}
      dataLoading={isLoading}
      actions={[
        {
          id: 'configure-alerts',
          label: 'Configurar Alertas',
          icon: Calendar,
          onClick: () => {},
          variant: 'outline',
          disabled: true,
        },
        {
          id: 'export-report',
          label: 'Exportar Reporte',
          icon: Download,
          onClick: () => {},
          variant: 'outline',
          disabled: true,
        },
      ]}
      filters={
        <div className="flex flex-col sm:flex-row gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              Período
            </label>
            <select
              value={selectedPeriod}
              onChange={(e) => setSelectedPeriod(e.target.value as TimePeriod)}
              className="px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-white"
            >
              {timeframes.map((timeframe) => (
                <option key={timeframe.value} value={timeframe.value}>
                  {timeframe.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      }
      stats={statsData}
      statsColumns={6}
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      showMobileNotice={true}
    >
        {/* Vista General Tab */}
        {activeTab === 'overview' && !isLoading && (
          <div className="space-y-6">
            {/* Department Comparison Matrix */}
            {departments && departments.length > 0 && (
              <AnalyticsCard title="Comparación de Departamentos">
                <div className="space-y-4">
                  {departments.map((dept) => (
                    <div key={dept.department_id} className="border border-[var(--border-primary)] rounded-lg p-5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] transition-all">
                      <div className="flex items-center justify-between mb-4">
                        <h4 className="font-semibold text-lg text-[var(--text-primary)]">
                          {dept.department_name}
                        </h4>
                        <div className="flex items-center space-x-3">
                          <span className="text-2xl font-bold text-[var(--text-primary)]">
                            {dept.efficiency.toFixed(1)}%
                          </span>
                          {getTrendIcon(dept.trend)}
                        </div>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div className="p-3 bg-[var(--bg-primary)] rounded-lg">
                          <p className="text-[var(--text-tertiary)] text-xs uppercase tracking-wide mb-1">
                            {dept.metrics.primary_metric.label}
                          </p>
                          <p className="font-bold text-lg text-[var(--text-primary)]">
                            {dept.metrics.primary_metric.value.toFixed(1)}
                            {dept.metrics.primary_metric.unit}
                          </p>
                        </div>
                        <div className="p-3 bg-[var(--bg-primary)] rounded-lg">
                          <p className="text-[var(--text-tertiary)] text-xs uppercase tracking-wide mb-1">
                            {dept.metrics.secondary_metric.label}
                          </p>
                          <p className="font-bold text-lg text-[var(--text-primary)]">
                            {dept.metrics.secondary_metric.value.toFixed(1)}
                            {dept.metrics.secondary_metric.unit}
                          </p>
                        </div>
                        <div className="p-3 bg-[var(--bg-primary)] rounded-lg">
                          <p className="text-[var(--text-tertiary)] text-xs uppercase tracking-wide mb-1">
                            {dept.metrics.tertiary_metric.label}
                          </p>
                          <p className="font-bold text-lg text-[var(--text-primary)]">
                            {dept.metrics.tertiary_metric.value.toFixed(1)}
                            {dept.metrics.tertiary_metric.unit}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </AnalyticsCard>
            )}

            {/* Process Efficiency Breakdown */}
            {processScore && (
              <AnalyticsCard title="Desglose de Eficiencia por Procesos">
                <div className="pt-4">
                  <ResponsiveContainer width="100%" height={350}>
                    <BarChart
                      data={[
                        { name: 'Producción', value: processScore.production_efficiency, weight: processScore.breakdown.production.weight },
                        { name: 'Inventario', value: processScore.inventory_efficiency, weight: processScore.breakdown.inventory.weight },
                        { name: 'Compras', value: processScore.procurement_efficiency, weight: processScore.breakdown.procurement.weight },
                        { name: 'Pedidos', value: processScore.order_efficiency, weight: processScore.breakdown.orders.weight },
                      ]}
                    >
                      <CartesianGrid strokeDasharray="3 3" stroke="var(--border-primary)" opacity={0.3} />
                      <XAxis
                        dataKey="name"
                        tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                        tickLine={{ stroke: 'var(--border-primary)' }}
                      />
                      <YAxis
                        tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                        tickLine={{ stroke: 'var(--border-primary)' }}
                      />
                      <Tooltip
                        contentStyle={{
                          backgroundColor: 'var(--bg-primary)',
                          border: '1px solid var(--border-primary)',
                          borderRadius: '8px',
                          boxShadow: 'var(--shadow-lg)'
                        }}
                        labelStyle={{ color: 'var(--text-primary)', fontWeight: 600 }}
                      />
                      <Legend wrapperStyle={{ paddingTop: '20px' }} />
                      <Bar dataKey="value" fill="var(--color-primary)" name="Eficiencia (%)" radius={[8, 8, 0, 0]} />
                      <Bar dataKey="weight" fill="var(--color-secondary)" name="Peso (%)" radius={[8, 8, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </AnalyticsCard>
            )}
          </div>
        )}

        {/* Eficiencia Operativa Tab */}
        {activeTab === 'efficiency' && !isLoading && (
          <>
            {/* Cycle Time Breakdown */}
            {cycleTime && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Análisis de Tiempo de Ciclo
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Pedido → Producción</p>
                    <p className="text-2xl font-bold text-[var(--text-primary)]">
                      {cycleTime.order_to_production_time.toFixed(1)}h
                    </p>
                  </div>
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Tiempo de Producción</p>
                    <p className="text-2xl font-bold text-[var(--text-primary)]">
                      {cycleTime.production_time.toFixed(1)}h
                    </p>
                  </div>
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Producción → Entrega</p>
                    <p className="text-2xl font-bold text-[var(--text-primary)]">
                      {cycleTime.production_to_delivery_time.toFixed(1)}h
                    </p>
                  </div>
                </div>
                <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                  <span className="text-sm font-medium">Tiempo Total de Ciclo</span>
                  <span className="text-xl font-bold text-[var(--color-primary)]">
                    {cycleTime.average_cycle_time.toFixed(1)}h
                  </span>
                </div>
              </Card>
            )}

            {/* Bottlenecks Analysis */}
            {bottlenecks && bottlenecks.bottlenecks.length > 0 && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Cuellos de Botella Detectados
                </h3>
                <div className="space-y-3">
                  {bottlenecks.bottlenecks.map((bottleneck, index) => (
                    <div
                      key={index}
                      className={`p-4 rounded-lg border ${
                        bottleneck.severity === 'high'
                          ? 'bg-red-50 border-red-200'
                          : 'bg-yellow-50 border-yellow-200'
                      }`}
                    >
                      <div className="flex items-start space-x-3">
                        <AlertCircle
                          className={`w-5 h-5 ${
                            bottleneck.severity === 'high' ? 'text-red-600' : 'text-yellow-600'
                          }`}
                        />
                        <div className="flex-1">
                          <div className="flex items-center justify-between">
                            <h4 className="text-sm font-medium text-[var(--text-primary)]">
                              {bottleneck.description}
                            </h4>
                            <Badge variant={bottleneck.severity === 'high' ? 'destructive' : 'default'}>
                              {bottleneck.area}
                            </Badge>
                          </div>
                          <p className="text-sm text-[var(--text-secondary)] mt-1">
                            {bottleneck.metric}: {bottleneck.value.toFixed(1)}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {/* Resource Utilization */}
            {resourceUtil && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Utilización de Recursos
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Equipamiento</p>
                    <p className="text-2xl font-bold text-[var(--text-primary)]">
                      {resourceUtil.equipment_utilization.toFixed(1)}%
                    </p>
                  </div>
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Inventario</p>
                    <p className="text-2xl font-bold text-[var(--text-primary)]">
                      {resourceUtil.inventory_utilization.toFixed(1)}%
                    </p>
                  </div>
                  <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Balance</p>
                    <p className="text-lg font-bold text-[var(--text-primary)]">
                      {resourceUtil.resource_balance === 'balanced' ? 'Equilibrado' : 'Desbalanceado'}
                    </p>
                  </div>
                </div>
              </Card>
            )}
          </>
        )}

        {/* Impacto de Calidad Tab */}
        {activeTab === 'quality' && !isLoading && (
          <>
            {/* Quality Index Overview */}
            {qualityIndex && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Índice de Calidad General
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div className="text-center p-6 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Calidad de Producción</p>
                    <p className="text-3xl font-bold text-[var(--text-primary)]">
                      {qualityIndex.production_quality.toFixed(1)}%
                    </p>
                  </div>
                  <div className="text-center p-6 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Calidad de Inventario</p>
                    <p className="text-3xl font-bold text-[var(--text-primary)]">
                      {qualityIndex.inventory_quality.toFixed(1)}%
                    </p>
                  </div>
                </div>
                <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                  <span className="text-sm font-medium">Índice de Calidad Combinado</span>
                  <span className="text-2xl font-bold text-green-600">
                    {qualityIndex.overall_quality_index.toFixed(1)}%
                  </span>
                </div>
              </Card>
            )}

            {/* Quality Issues Breakdown */}
            {qualityIndex && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Desglose de Problemas de Calidad
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <span className="text-sm font-medium">Defectos de Producción</span>
                    <span className="text-lg font-semibold text-red-600">
                      {qualityIndex.quality_issues.production_defects.toFixed(1)}%
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <span className="text-sm font-medium">Desperdicio</span>
                    <span className="text-lg font-semibold text-orange-600">
                      {qualityIndex.quality_issues.waste_percentage.toFixed(1)}%
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <span className="text-sm font-medium">Items por Vencer</span>
                    <span className="text-lg font-semibold text-yellow-600">
                      {qualityIndex.quality_issues.expiring_items}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <span className="text-sm font-medium">Stock Bajo Afectando Calidad</span>
                    <span className="text-lg font-semibold text-yellow-600">
                      {qualityIndex.quality_issues.low_stock_affecting_quality}
                    </span>
                  </div>
                </div>
              </Card>
            )}
          </>
        )}

        {/* Optimización Tab */}
        {activeTab === 'optimization' && !isLoading && (
          <>
            {/* Cost-Revenue Analysis */}
            {costRevenue && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Análisis de Rentabilidad
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div className="text-center p-6 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Ingresos Totales</p>
                    <p className="text-3xl font-bold text-green-600">
                      {currencySymbol}{costRevenue.total_revenue.toLocaleString('es-ES')}
                    </p>
                  </div>
                  <div className="text-center p-6 bg-[var(--bg-secondary)] rounded-lg">
                    <p className="text-sm text-[var(--text-secondary)] mb-2">Costos Estimados</p>
                    <p className="text-3xl font-bold text-red-600">
                      {currencySymbol}{costRevenue.estimated_costs.toLocaleString('es-ES')}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                    <span className="text-sm font-medium">Ratio Costo-Ingreso</span>
                    <span className="text-xl font-bold text-[var(--color-primary)]">
                      {costRevenue.cost_revenue_ratio.toFixed(1)}%
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                    <span className="text-sm font-medium">Margen de Beneficio</span>
                    <span className="text-xl font-bold text-green-600">
                      {costRevenue.profit_margin.toFixed(1)}%
                    </span>
                  </div>
                </div>
              </Card>
            )}

            {/* Improvement Recommendations */}
            {bottlenecks && bottlenecks.total_bottlenecks > 0 && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Recomendaciones de Mejora
                </h3>
                <div className="space-y-4">
                  <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <h4 className="font-medium text-[var(--text-primary)] mb-2">
                      Área más crítica: {bottlenecks.most_critical_area}
                    </h4>
                    <p className="text-sm text-[var(--text-secondary)]">
                      Se han detectado {bottlenecks.critical_count} cuellos de botella críticos.
                      Prioriza la optimización de esta área para mejorar el flujo general.
                    </p>
                  </div>
                  {qualityIndex && qualityIndex.waste_impact > 5 && (
                    <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                      <h4 className="font-medium text-[var(--text-primary)] mb-2">
                        Reducir Desperdicio
                      </h4>
                      <p className="text-sm text-[var(--text-secondary)]">
                        El desperdicio actual es de {qualityIndex.waste_impact.toFixed(1)}%.
                        Implementa controles de calidad más estrictos para reducir pérdidas.
                      </p>
                    </div>
                  )}
                  {resourceUtil && resourceUtil.resource_balance === 'imbalanced' && (
                    <div className="p-4 bg-orange-50 border border-orange-200 rounded-lg">
                      <h4 className="font-medium text-[var(--text-primary)] mb-2">
                        Balance de Recursos
                      </h4>
                      <p className="text-sm text-[var(--text-secondary)]">
                        Los recursos están desbalanceados entre departamentos.
                        Considera redistribuir para optimizar la utilización general.
                      </p>
                    </div>
                  )}
                </div>
              </Card>
            )}

            {/* No Recommendations */}
            {(!bottlenecks || bottlenecks.total_bottlenecks === 0) && (
              <Card className="p-6">
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
                  Recomendaciones de Mejora
                </h3>
                <div className="text-center py-8">
                  <Target className="w-12 h-12 mx-auto text-[var(--color-success)] mb-3" />
                  <p className="text-[var(--text-secondary)]">
                    ¡Excelente! No se han detectado áreas críticas que requieran optimización inmediata.
                  </p>
                </div>
              </Card>
            )}
          </>
        )}
    </AnalyticsPageLayout>
  );
};

export default PerformanceAnalyticsPage;
