import React, { useState } from 'react';
import { Activity, Clock, Users, TrendingUp, Target, AlertCircle, Download, Calendar } from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';

const PerformanceAnalyticsPage: React.FC = () => {
  const [selectedTimeframe, setSelectedTimeframe] = useState('month');
  const [selectedMetric, setSelectedMetric] = useState('efficiency');

  const performanceMetrics = {
    overallEfficiency: 87.5,
    productionTime: 4.2,
    qualityScore: 92.1,
    employeeProductivity: 89.3,
    customerSatisfaction: 94.7,
    resourceUtilization: 78.9,
  };

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

  const departmentPerformance = [
    {
      department: 'Producción',
      efficiency: 91.2,
      trend: 5.3,
      issues: 2,
      employees: 8,
      metrics: {
        avgBatchTime: '2.3h',
        qualityRate: '94%',
        wastePercentage: '3.1%'
      }
    },
    {
      department: 'Ventas',
      efficiency: 88.7,
      trend: -1.2,
      issues: 1,
      employees: 4,
      metrics: {
        avgServiceTime: '3.2min',
        customerWaitTime: '2.1min',
        salesPerHour: '€127'
      }
    },
    {
      department: 'Inventario',
      efficiency: 82.4,
      trend: 2.8,
      issues: 3,
      employees: 2,
      metrics: {
        stockAccuracy: '96.7%',
        turnoverRate: '12.3',
        wastageRate: '4.2%'
      }
    },
    {
      department: 'Administración',
      efficiency: 94.1,
      trend: 8.1,
      issues: 0,
      employees: 3,
      metrics: {
        responseTime: '1.2h',
        taskCompletion: '98%',
        documentAccuracy: '99.1%'
      }
    }
  ];

  const kpiTrends = [
    {
      name: 'Eficiencia General',
      current: 87.5,
      target: 90.0,
      previous: 84.2,
      unit: '%',
      color: 'blue'
    },
    {
      name: 'Tiempo de Producción',
      current: 4.2,
      target: 4.0,
      previous: 4.5,
      unit: 'h',
      color: 'green',
      inverse: true
    },
    {
      name: 'Satisfacción Cliente',
      current: 94.7,
      target: 95.0,
      previous: 93.1,
      unit: '%',
      color: 'purple'
    },
    {
      name: 'Utilización de Recursos',
      current: 78.9,
      target: 85.0,
      previous: 76.3,
      unit: '%',
      color: 'orange'
    }
  ];

  const performanceAlerts = [
    {
      id: '1',
      type: 'warning',
      title: 'Eficiencia de Inventario Baja',
      description: 'El departamento de inventario está por debajo del objetivo del 85%',
      value: '82.4%',
      target: '85%',
      department: 'Inventario'
    },
    {
      id: '2',
      type: 'info',
      title: 'Tiempo de Producción Mejorado',
      description: 'El tiempo promedio de producción ha mejorado este mes',
      value: '4.2h',
      target: '4.0h',
      department: 'Producción'
    },
    {
      id: '3',
      type: 'success',
      title: 'Administración Supera Objetivos',
      description: 'El departamento administrativo está funcionando por encima del objetivo',
      value: '94.1%',
      target: '90%',
      department: 'Administración'
    }
  ];

  const productivityData = [
    { hour: '07:00', efficiency: 75, transactions: 12, employees: 3 },
    { hour: '08:00', efficiency: 82, transactions: 18, employees: 5 },
    { hour: '09:00', efficiency: 89, transactions: 28, employees: 6 },
    { hour: '10:00', efficiency: 91, transactions: 32, employees: 7 },
    { hour: '11:00', efficiency: 94, transactions: 38, employees: 8 },
    { hour: '12:00', efficiency: 96, transactions: 45, employees: 8 },
    { hour: '13:00', efficiency: 95, transactions: 42, employees: 8 },
    { hour: '14:00', efficiency: 88, transactions: 35, employees: 7 },
    { hour: '15:00', efficiency: 85, transactions: 28, employees: 6 },
    { hour: '16:00', efficiency: 83, transactions: 25, employees: 5 },
    { hour: '17:00', efficiency: 87, transactions: 31, employees: 6 },
    { hour: '18:00', efficiency: 90, transactions: 38, employees: 7 },
    { hour: '19:00', efficiency: 86, transactions: 29, employees: 5 },
    { hour: '20:00', efficiency: 78, transactions: 18, employees: 3 },
  ];

  const getTrendIcon = (trend: number) => {
    if (trend > 0) {
      return <TrendingUp className="w-4 h-4 text-[var(--color-success)]" />;
    } else {
      return <TrendingUp className="w-4 h-4 text-[var(--color-error)] transform rotate-180" />;
    }
  };

  const getTrendColor = (trend: number) => {
    return trend >= 0 ? 'text-[var(--color-success)]' : 'text-[var(--color-error)]';
  };

  const getPerformanceColor = (value: number, target: number, inverse = false) => {
    const comparison = inverse ? value < target : value >= target;
    return comparison ? 'text-[var(--color-success)]' : value >= target * 0.9 ? 'text-yellow-600' : 'text-[var(--color-error)]';
  };

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

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

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Análisis de Rendimiento"
        description="Monitorea la eficiencia operativa y el rendimiento de todos los departamentos"
        action={
          <div className="flex space-x-2">
            <Button variant="outline">
              <Calendar className="w-4 h-4 mr-2" />
              Configurar Alertas
            </Button>
            <Button variant="outline">
              <Download className="w-4 h-4 mr-2" />
              Exportar Reporte
            </Button>
          </div>
        }
      />

      {/* Controls */}
      <Card className="p-6">
        <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={selectedTimeframe}
              onChange={(e) => setSelectedTimeframe(e.target.value)}
              className="px-3 py-2 border border-[var(--border-secondary)] rounded-md"
            >
              {timeframes.map(timeframe => (
                <option key={timeframe.value} value={timeframe.value}>{timeframe.label}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Métrica Principal</label>
            <select
              value={selectedMetric}
              onChange={(e) => setSelectedMetric(e.target.value)}
              className="px-3 py-2 border border-[var(--border-secondary)] rounded-md"
            >
              <option value="efficiency">Eficiencia</option>
              <option value="productivity">Productividad</option>
              <option value="quality">Calidad</option>
              <option value="satisfaction">Satisfacción</option>
            </select>
          </div>
        </div>
      </Card>

      {/* KPI Overview */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {kpiTrends.map((kpi) => (
          <Card key={kpi.name} className="p-6">
            <div className="flex items-center justify-between mb-2">
              <h3 className="text-sm font-medium text-[var(--text-secondary)]">{kpi.name}</h3>
              <div className={`w-3 h-3 rounded-full bg-${kpi.color}-500`}></div>
            </div>
            <div className="flex items-end justify-between">
              <div>
                <p className={`text-2xl font-bold ${getPerformanceColor(kpi.current, kpi.target, kpi.inverse)}`}>
                  {kpi.current}{kpi.unit}
                </p>
                <p className="text-xs text-[var(--text-tertiary)]">
                  Objetivo: {kpi.target}{kpi.unit}
                </p>
              </div>
              <div className="text-right">
                <div className="flex items-center">
                  {getTrendIcon(kpi.current - kpi.previous)}
                  <span className={`text-sm ml-1 ${getTrendColor(kpi.current - kpi.previous)}`}>
                    {Math.abs(kpi.current - kpi.previous).toFixed(1)}{kpi.unit}
                  </span>
                </div>
              </div>
            </div>
            <div className="mt-3 w-full bg-[var(--bg-quaternary)] rounded-full h-2">
              <div
                className={`bg-${kpi.color}-500 h-2 rounded-full transition-all duration-300`}
                style={{ width: `${Math.min((kpi.current / kpi.target) * 100, 100)}%` }}
              ></div>
            </div>
          </Card>
        ))}
      </div>

      {/* Performance Alerts */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Alertas de Rendimiento</h3>
        <div className="space-y-3">
          {performanceAlerts.map((alert) => (
            <div key={alert.id} className={`p-4 rounded-lg border ${getAlertColor(alert.type)}`}>
              <div className="flex items-start space-x-3">
                {getAlertIcon(alert.type)}
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-medium text-[var(--text-primary)]">{alert.title}</h4>
                    <Badge variant="gray">{alert.department}</Badge>
                  </div>
                  <p className="text-sm text-[var(--text-secondary)] mt-1">{alert.description}</p>
                  <div className="flex items-center space-x-4 mt-2">
                    <span className="text-sm">
                      <strong>Actual:</strong> {alert.value}
                    </span>
                    <span className="text-sm">
                      <strong>Objetivo:</strong> {alert.target}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Department Performance */}
        <Card className="p-6">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Rendimiento por Departamento</h3>
          <div className="space-y-4">
            {departmentPerformance.map((dept) => (
              <div key={dept.department} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center space-x-3">
                    <h4 className="font-medium text-[var(--text-primary)]">{dept.department}</h4>
                    <Badge variant="gray">{dept.employees} empleados</Badge>
                  </div>
                  <div className="flex items-center space-x-2">
                    <span className="text-lg font-semibold text-[var(--text-primary)]">
                      {dept.efficiency}%
                    </span>
                    <div className="flex items-center">
                      {getTrendIcon(dept.trend)}
                      <span className={`text-sm ml-1 ${getTrendColor(dept.trend)}`}>
                        {Math.abs(dept.trend).toFixed(1)}%
                      </span>
                    </div>
                  </div>
                </div>
                
                <div className="grid grid-cols-3 gap-4 text-sm">
                  {Object.entries(dept.metrics).map(([key, value]) => (
                    <div key={key}>
                      <p className="text-[var(--text-tertiary)] text-xs">
                        {key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}
                      </p>
                      <p className="font-medium">{value}</p>
                    </div>
                  ))}
                </div>

                {dept.issues > 0 && (
                  <div className="mt-3 flex items-center text-sm text-[var(--color-warning)]">
                    <AlertCircle className="w-4 h-4 mr-1" />
                    {dept.issues} problema{dept.issues > 1 ? 's' : ''} detectado{dept.issues > 1 ? 's' : ''}
                  </div>
                )}
              </div>
            ))}
          </div>
        </Card>

        {/* Hourly Productivity */}
        <Card className="p-6">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Eficiencia por Hora</h3>
          <div className="h-64 flex items-end space-x-1 justify-between">
            {productivityData.map((data, index) => (
              <div key={index} className="flex flex-col items-center flex-1">
                <div className="text-xs text-[var(--text-secondary)] mb-1">{data.efficiency}%</div>
                <div
                  className="w-full bg-[var(--color-info)]/50 rounded-t"
                  style={{
                    height: `${(data.efficiency / 100) * 200}px`,
                    minHeight: '8px',
                    backgroundColor: data.efficiency >= 90 ? '#10B981' : data.efficiency >= 80 ? '#F59E0B' : '#EF4444'
                  }}
                ></div>
                <span className="text-xs text-[var(--text-tertiary)] mt-2 transform -rotate-45 origin-center">
                  {data.hour}
                </span>
              </div>
            ))}
          </div>
          <div className="mt-4 flex justify-center space-x-6 text-xs">
            <div className="flex items-center">
              <div className="w-3 h-3 bg-green-500 rounded mr-1"></div>
              <span>≥90% Excelente</span>
            </div>
            <div className="flex items-center">
              <div className="w-3 h-3 bg-yellow-500 rounded mr-1"></div>
              <span>80-89% Bueno</span>
            </div>
            <div className="flex items-center">
              <div className="w-3 h-3 bg-red-500 rounded mr-1"></div>
              <span>&lt;80% Bajo</span>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default PerformanceAnalyticsPage;