import React, { useState } from 'react';
import {
  ShoppingCart,
  TrendingUp,
  AlertCircle,
  AlertTriangle,
  Target,
  DollarSign,
  Award,
  BarChart3,
  Truck,
  Calendar
} from 'lucide-react';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend
} from 'recharts';
import { AnalyticsPageLayout, AnalyticsCard } from '../../../components/analytics';
import { useSubscription } from '../../../api/hooks/subscription';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useProcurementDashboard, useProcurementTrends } from '../../../api/hooks/procurement';
import { formatters } from '../../../components/ui/Stats/StatsPresets';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

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

  const [activeTab, setActiveTab] = useState('overview');

  const { data: dashboard, isLoading: dashboardLoading } = useProcurementDashboard(tenantId);
  const { data: trends, isLoading: trendsLoading } = useProcurementTrends(tenantId, 7);

  // Check if user has access to advanced analytics (professional/enterprise)
  const hasAdvancedAccess = canAccessAnalytics('advanced');

  // Tab configuration
  const tabs = [
    {
      id: 'overview',
      label: 'Resumen',
      icon: BarChart3
    },
    {
      id: 'performance',
      label: 'Rendimiento',
      icon: TrendingUp
    },
    {
      id: 'suppliers',
      label: 'Proveedores',
      icon: Truck
    },
    {
      id: 'costs',
      label: 'Costos',
      icon: DollarSign
    },
    {
      id: 'quality',
      label: 'Calidad',
      icon: Award
    }
  ];

  return (
    <AnalyticsPageLayout
      title="Analítica de Compras"
      description="Insights avanzados sobre planificación de compras y gestión de proveedores"
      subscriptionLoading={subscriptionInfo.loading}
      hasAccess={hasAdvancedAccess}
      dataLoading={dashboardLoading}
      stats={[
        {
          title: 'Planes Activos',
          value: dashboard?.summary?.total_plans || 0,
          icon: ShoppingCart,
          formatter: formatters.number
        },
        {
          title: 'Tasa de Cumplimiento',
          value: dashboard?.performance_metrics?.average_fulfillment_rate || 0,
          icon: Target,
          formatter: formatters.percentage
        },
        {
          title: 'Entregas a Tiempo',
          value: dashboard?.performance_metrics?.average_on_time_delivery || 0,
          icon: Calendar,
          formatter: formatters.percentage
        },
        {
          title: 'Variación de Costos',
          value: dashboard?.performance_metrics?.cost_accuracy || 0,
          icon: DollarSign,
          formatter: formatters.percentage
        }
      ]}
      statsColumns={4}
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      showMobileNotice={true}
    >
        {activeTab === 'overview' && (
          <div className="space-y-6">
            {/* Overview Tab */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Plan Status Distribution */}
              <AnalyticsCard title="Distribución de Estados de Planes">
                  <div className="space-y-3">
                    {dashboard?.plan_status_distribution?.map((status: any) => (
                      <div key={status.status} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
                        <span className="text-sm font-medium text-[var(--text-primary)] capitalize">{status.status.replace('_', ' ')}</span>
                        <div className="flex items-center gap-3">
                          <div className="w-32 h-2 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
                            <div
                              className="h-full bg-[var(--color-primary)] rounded-full transition-all"
                              style={{ width: `${(status.count / (dashboard?.summary?.total_plans || 1)) * 100}%` }}
                            />
                          </div>
                          <span className="text-sm font-bold text-[var(--text-primary)] w-10 text-right">
                            {status.count}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
              </AnalyticsCard>

              {/* Critical Requirements */}
              <AnalyticsCard
                title="Requerimientos Críticos"
                actions={<AlertCircle className="h-5 w-5 text-[var(--color-error)]" />}
              >
                  <div className="space-y-3">
                    <div className="flex justify-between items-center p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-[var(--color-error)]"></div>
                        <span className="text-sm font-medium text-[var(--text-secondary)]">Stock Crítico</span>
                      </div>
                      <span className="text-2xl font-bold text-[var(--color-error)]">
                        {dashboard?.critical_requirements?.low_stock || 0}
                      </span>
                    </div>
                    <div className="flex justify-between items-center p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-[var(--color-warning)]"></div>
                        <span className="text-sm font-medium text-[var(--text-secondary)]">Entregas Atrasadas</span>
                      </div>
                      <span className="text-2xl font-bold text-[var(--color-warning)]">
                        {dashboard?.critical_requirements?.overdue || 0}
                      </span>
                    </div>
                    <div className="flex justify-between items-center p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-[var(--color-info)]"></div>
                        <span className="text-sm font-medium text-[var(--text-secondary)]">Alta Prioridad</span>
                      </div>
                      <span className="text-2xl font-bold text-[var(--color-info)]">
                        {dashboard?.critical_requirements?.high_priority || 0}
                      </span>
                    </div>
                  </div>
              </AnalyticsCard>
            </div>

            {/* Recent Plans */}
            <AnalyticsCard title="Planes Recientes">
                <div className="overflow-x-auto -mx-6">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-[var(--border-primary)] bg-[var(--bg-secondary)]">
                        <th className="text-left py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Plan</th>
                        <th className="text-left py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Fecha</th>
                        <th className="text-left py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Estado</th>
                        <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Requerimientos</th>
                        <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Costo Total</th>
                      </tr>
                    </thead>
                    <tbody>
                      {dashboard?.recent_plans?.map((plan: any) => (
                        <tr key={plan.id} className="border-b border-[var(--border-primary)] hover:bg-[var(--bg-secondary)] transition-colors">
                          <td className="py-4 px-6 text-sm font-medium text-[var(--text-primary)]">{plan.plan_number}</td>
                          <td className="py-4 px-6 text-sm text-[var(--text-secondary)]">
                            {new Date(plan.plan_date).toLocaleDateString()}
                          </td>
                          <td className="py-4 px-6">
                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(plan.status)}`}>
                              {plan.status}
                            </span>
                          </td>
                          <td className="py-4 px-6 text-sm text-right font-medium text-[var(--text-primary)]">
                            {plan.total_requirements}
                          </td>
                          <td className="py-4 px-6 text-sm text-right font-bold text-[var(--text-primary)]">
                            {currencySymbol}{formatters.currency(plan.total_estimated_cost, '')}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
            </AnalyticsCard>
          </div>
        )}

        {activeTab === 'performance' && (
          <div className="space-y-6">
            {/* Performance Tab */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <AnalyticsCard>
                <div className="text-center p-4">
                  <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 dark:bg-green-900/30 mb-4">
                    <Target className="h-8 w-8 text-[var(--color-success)]" />
                  </div>
                  <div className="text-4xl font-bold text-[var(--text-primary)] mb-2">
                    {formatters.percentage(dashboard?.performance_metrics?.average_fulfillment_rate || 0)}
                  </div>
                  <div className="text-sm font-medium text-[var(--text-secondary)]">Tasa de Cumplimiento</div>
                </div>
              </AnalyticsCard>

              <AnalyticsCard>
                <div className="text-center p-4">
                  <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900/30 mb-4">
                    <Calendar className="h-8 w-8 text-[var(--color-info)]" />
                  </div>
                  <div className="text-4xl font-bold text-[var(--text-primary)] mb-2">
                    {formatters.percentage(dashboard?.performance_metrics?.average_on_time_delivery || 0)}
                  </div>
                  <div className="text-sm font-medium text-[var(--text-secondary)]">Entregas a Tiempo</div>
                </div>
              </AnalyticsCard>

              <AnalyticsCard>
                <div className="text-center p-4">
                  <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-orange-100 dark:bg-orange-900/30 mb-4">
                    <Award className="h-8 w-8 text-[var(--color-warning)]" />
                  </div>
                  <div className="text-4xl font-bold text-[var(--text-primary)] mb-2">
                    {dashboard?.performance_metrics?.supplier_performance?.toFixed(1) || '0.0'}
                  </div>
                  <div className="text-sm font-medium text-[var(--text-secondary)]">Puntuación de Calidad</div>
                </div>
              </AnalyticsCard>
            </div>

            {/* Performance Trend Chart */}
            <AnalyticsCard title="Tendencias de Rendimiento (Últimos 7 días)" loading={trendsLoading}>
              {trends && trends.performance_trend && trends.performance_trend.length > 0 ? (
                <div className="pt-4">
                  <ResponsiveContainer width="100%" height={350}>
                    <LineChart data={trends.performance_trend}>
                      <CartesianGrid strokeDasharray="3 3" stroke="var(--border-primary)" opacity={0.3} />
                      <XAxis
                        dataKey="date"
                        stroke="var(--text-tertiary)"
                        tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                        tickLine={{ stroke: 'var(--border-primary)' }}
                      />
                      <YAxis
                        stroke="var(--text-tertiary)"
                        tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                        tickFormatter={(value) => `${(value * 100).toFixed(0)}%`}
                        tickLine={{ stroke: 'var(--border-primary)' }}
                      />
                      <Tooltip
                        contentStyle={{
                          backgroundColor: 'var(--bg-primary)',
                          border: '1px solid var(--border-primary)',
                          borderRadius: '8px',
                          boxShadow: 'var(--shadow-lg)'
                        }}
                        formatter={(value: any) => `${(value * 100).toFixed(1)}%`}
                        labelStyle={{ color: 'var(--text-primary)', fontWeight: 600 }}
                      />
                      <Legend wrapperStyle={{ paddingTop: '20px' }} />
                      <Line
                        type="monotone"
                        dataKey="fulfillment_rate"
                        stroke="var(--color-success)"
                        strokeWidth={3}
                        name="Tasa de Cumplimiento"
                        dot={{ fill: 'var(--color-success)', r: 4 }}
                        activeDot={{ r: 6 }}
                      />
                      <Line
                        type="monotone"
                        dataKey="on_time_rate"
                        stroke="var(--color-info)"
                        strokeWidth={3}
                        name="Entregas a Tiempo"
                        dot={{ fill: 'var(--color-info)', r: 4 }}
                        activeDot={{ r: 6 }}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              ) : (
                <div className="h-80 flex flex-col items-center justify-center text-[var(--text-tertiary)]">
                  <BarChart3 className="h-16 w-16 mb-4 opacity-20" />
                  <p className="text-sm">No hay datos de tendencias disponibles</p>
                </div>
              )}
            </AnalyticsCard>
          </div>
        )}

        {activeTab === 'suppliers' && (
          <div className="space-y-6">
            {/* Suppliers Tab */}
            <AnalyticsCard title="Rendimiento de Proveedores">
              <div className="overflow-x-auto -mx-6">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-[var(--border-primary)] bg-[var(--bg-secondary)]">
                      <th className="text-left py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Proveedor</th>
                      <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Órdenes</th>
                      <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Cumplimiento</th>
                      <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Puntualidad</th>
                      <th className="text-right py-3 px-6 text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">Calidad</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dashboard?.supplier_performance?.map((supplier: any) => (
                      <tr key={supplier.id} className="border-b border-[var(--border-primary)] hover:bg-[var(--bg-secondary)] transition-colors">
                        <td className="py-4 px-6 text-sm font-semibold text-[var(--text-primary)]">{supplier.name}</td>
                        <td className="py-4 px-6 text-sm text-right font-medium text-[var(--text-primary)]">
                          <span className="inline-flex items-center justify-center px-3 py-1 rounded-full bg-[var(--bg-tertiary)]">
                            {supplier.total_orders}
                          </span>
                        </td>
                        <td className="py-4 px-6 text-sm text-right">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full font-semibold ${
                            supplier.fulfillment_rate >= 0.9 ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' :
                            supplier.fulfillment_rate >= 0.7 ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300' :
                            'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300'
                          }`}>
                            {formatters.percentage(supplier.fulfillment_rate)}
                          </span>
                        </td>
                        <td className="py-4 px-6 text-sm text-right">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full font-semibold ${
                            supplier.on_time_rate >= 0.9 ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' :
                            supplier.on_time_rate >= 0.7 ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300' :
                            'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300'
                          }`}>
                            {formatters.percentage(supplier.on_time_rate)}
                          </span>
                        </td>
                        <td className="py-4 px-6 text-sm text-right">
                          <span className="font-bold text-[var(--text-primary)]">
                            {supplier.quality_score?.toFixed(1) || 'N/A'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </AnalyticsCard>
          </div>
        )}

        {activeTab === 'costs' && (
          <div className="space-y-6">
            {/* Costs Tab */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <AnalyticsCard title="Análisis de Costos">
                <div className="space-y-4">
                  <div className="flex justify-between items-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <div>
                      <span className="text-xs text-[var(--text-tertiary)] uppercase tracking-wide">Costo Total Estimado</span>
                      <div className="text-3xl font-bold text-[var(--text-primary)] mt-1">
                        {currencySymbol}{formatters.currency(dashboard?.summary?.total_estimated_cost || 0, '')}
                      </div>
                    </div>
                    <DollarSign className="h-12 w-12 text-[var(--color-info)] opacity-20" />
                  </div>
                  <div className="flex justify-between items-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <div>
                      <span className="text-xs text-[var(--text-tertiary)] uppercase tracking-wide">Costo Total Aprobado</span>
                      <div className="text-3xl font-bold text-[var(--text-primary)] mt-1">
                        {currencySymbol}{formatters.currency(dashboard?.summary?.total_approved_cost || 0, '')}
                      </div>
                    </div>
                    <DollarSign className="h-12 w-12 text-[var(--color-success)] opacity-20" />
                  </div>
                  <div className="flex justify-between items-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                    <div>
                      <span className="text-xs text-[var(--text-tertiary)] uppercase tracking-wide">Variación Promedio</span>
                      <div className={`text-3xl font-bold mt-1 ${
                        (dashboard?.summary?.cost_variance || 0) > 0
                          ? 'text-[var(--color-error)]'
                          : 'text-[var(--color-success)]'
                      }`}>
                        {(dashboard?.summary?.cost_variance || 0) > 0 ? '+' : ''}{currencySymbol}{formatters.currency(dashboard?.summary?.cost_variance || 0, '')}
                      </div>
                    </div>
                    <TrendingUp className={`h-12 w-12 opacity-20 ${
                      (dashboard?.summary?.cost_variance || 0) > 0
                        ? 'text-[var(--color-error)]'
                        : 'text-[var(--color-success)] rotate-180'
                    }`} />
                  </div>
                </div>
              </AnalyticsCard>

              <AnalyticsCard title="Distribución de Costos por Categoría">
                <div className="space-y-4">
                  {dashboard?.cost_by_category?.map((category: any) => (
                    <div key={category.name} className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-[var(--text-primary)]">{category.name}</span>
                        <span className="text-sm font-bold text-[var(--text-primary)]">
                          {currencySymbol}{formatters.currency(category.amount, '')}
                        </span>
                      </div>
                      <div className="relative">
                        <div className="w-full h-3 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
                          <div
                            className="h-full bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-light)] rounded-full transition-all"
                            style={{ width: `${(category.amount / (dashboard?.summary?.total_estimated_cost || 1)) * 100}%` }}
                          />
                        </div>
                        <span className="absolute -top-1 right-0 text-xs font-medium text-[var(--text-tertiary)]">
                          {((category.amount / (dashboard?.summary?.total_estimated_cost || 1)) * 100).toFixed(1)}%
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </AnalyticsCard>
            </div>
          </div>
        )}

        {activeTab === 'quality' && (
          <div className="space-y-6">
            {/* Quality Tab */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <AnalyticsCard title="Métricas de Calidad">
                <div className="space-y-4">
                  <div className="flex flex-col items-center p-6 bg-gradient-to-br from-[var(--color-primary)]/10 to-[var(--color-primary-light)]/5 rounded-lg">
                    <span className="text-sm text-[var(--text-secondary)] mb-2">Puntuación Promedio</span>
                    <div className="flex items-baseline gap-1">
                      <span className="text-5xl font-bold text-[var(--text-primary)]">
                        {dashboard?.quality_metrics?.avg_score?.toFixed(1) || '0.0'}
                      </span>
                      <span className="text-2xl font-medium text-[var(--text-secondary)]">/ 10</span>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex flex-col items-center p-4 bg-green-50 dark:bg-green-900/20 rounded-lg">
                      <Award className="h-8 w-8 text-[var(--color-success)] mb-2" />
                      <span className="text-2xl font-bold text-[var(--color-success)]">
                        {dashboard?.quality_metrics?.high_quality_count || 0}
                      </span>
                      <span className="text-xs text-[var(--text-secondary)] text-center mt-1">Calidad Alta</span>
                    </div>
                    <div className="flex flex-col items-center p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
                      <AlertTriangle className="h-8 w-8 text-[var(--color-error)] mb-2" />
                      <span className="text-2xl font-bold text-[var(--color-error)]">
                        {dashboard?.quality_metrics?.low_quality_count || 0}
                      </span>
                      <span className="text-xs text-[var(--text-secondary)] text-center mt-1">Calidad Baja</span>
                    </div>
                  </div>
                </div>
              </AnalyticsCard>

              <AnalyticsCard title="Tendencia de Calidad (Últimos 7 días)" loading={trendsLoading}>
                {trends && trends.quality_trend && trends.quality_trend.length > 0 ? (
                  <div className="pt-4">
                    <ResponsiveContainer width="100%" height={280}>
                      <LineChart data={trends.quality_trend}>
                        <CartesianGrid strokeDasharray="3 3" stroke="var(--border-primary)" opacity={0.3} />
                        <XAxis
                          dataKey="date"
                          stroke="var(--text-tertiary)"
                          tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                          tickLine={{ stroke: 'var(--border-primary)' }}
                        />
                        <YAxis
                          stroke="var(--text-tertiary)"
                          tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                          domain={[0, 10]}
                          ticks={[0, 2, 4, 6, 8, 10]}
                          tickLine={{ stroke: 'var(--border-primary)' }}
                        />
                        <Tooltip
                          contentStyle={{
                            backgroundColor: 'var(--bg-primary)',
                            border: '1px solid var(--border-primary)',
                            borderRadius: '8px',
                            boxShadow: 'var(--shadow-lg)'
                          }}
                          formatter={(value: any) => `${value.toFixed(1)} / 10`}
                          labelStyle={{ color: 'var(--text-primary)', fontWeight: 600 }}
                        />
                        <Line
                          type="monotone"
                          dataKey="quality_score"
                          stroke="var(--color-warning)"
                          strokeWidth={3}
                          name="Puntuación de Calidad"
                          dot={{ fill: 'var(--color-warning)', r: 4 }}
                          activeDot={{ r: 6 }}
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  </div>
                ) : (
                  <div className="h-80 flex flex-col items-center justify-center text-[var(--text-tertiary)]">
                    <Award className="h-16 w-16 mb-4 opacity-20" />
                    <p className="text-sm">No hay datos de calidad disponibles</p>
                  </div>
                )}
              </AnalyticsCard>
            </div>
          </div>
        )}
    </AnalyticsPageLayout>
  );
};

// Helper function for status colors
function getStatusColor(status: string): string {
  const colors: Record<string, string> = {
    draft: 'bg-[var(--bg-tertiary)] text-[var(--text-secondary)]',
    pending_approval: 'bg-yellow-100 text-yellow-800',
    approved: 'bg-green-100 text-green-800',
    in_execution: 'bg-blue-100 text-blue-800',
    completed: 'bg-green-100 text-green-800',
    cancelled: 'bg-red-100 text-red-800'
  };
  return colors[status] || colors.draft;
}

export default ProcurementAnalyticsPage;
