import React from 'react';
import { useTranslation } from 'react-i18next';
import { Settings, AlertTriangle, CheckCircle, Clock, Zap } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Badge, Button } from '../../../../ui';
import { useCurrentTenant } from '../../../../../stores/tenant.store';

interface EquipmentStatus {
  id: string;
  name: string;
  type: 'oven' | 'mixer' | 'proofer' | 'packaging';
  status: 'operational' | 'warning' | 'maintenance' | 'down';
  efficiency: number;
  temperature?: number;
  uptime: number;
  lastMaintenance: string;
  nextMaintenance: string;
  alertCount: number;
}

export const EquipmentStatusWidget: React.FC = () => {
  const { t } = useTranslation('production');
  const currentTenant = useCurrentTenant();

  // Mock equipment data - replace with real API call
  const equipment: EquipmentStatus[] = [
    {
      id: '1',
      name: 'Horno Principal',
      type: 'oven',
      status: 'operational',
      efficiency: 94,
      temperature: 180,
      uptime: 98.5,
      lastMaintenance: '2024-01-15',
      nextMaintenance: '2024-02-15',
      alertCount: 0
    },
    {
      id: '2',
      name: 'Mezcladora A',
      type: 'mixer',
      status: 'warning',
      efficiency: 87,
      uptime: 85.2,
      lastMaintenance: '2024-01-10',
      nextMaintenance: '2024-02-10',
      alertCount: 2
    },
    {
      id: '3',
      name: 'Cámara de Fermentación 1',
      type: 'proofer',
      status: 'operational',
      efficiency: 96,
      temperature: 28,
      uptime: 99.1,
      lastMaintenance: '2024-01-20',
      nextMaintenance: '2024-02-20',
      alertCount: 0
    },
    {
      id: '4',
      name: 'Empaquetadora',
      type: 'packaging',
      status: 'maintenance',
      efficiency: 0,
      uptime: 0,
      lastMaintenance: '2024-01-25',
      nextMaintenance: '2024-01-26',
      alertCount: 1
    }
  ];

  const getStatusColor = (status: EquipmentStatus['status']) => {
    switch (status) {
      case 'operational': return 'text-green-600';
      case 'warning': return 'text-orange-600';
      case 'maintenance': return 'text-blue-600';
      case 'down': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  const getStatusBadgeVariant = (status: EquipmentStatus['status']) => {
    switch (status) {
      case 'operational': return 'success';
      case 'warning': return 'warning';
      case 'maintenance': return 'info';
      case 'down': return 'error';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: EquipmentStatus['status']) => {
    switch (status) {
      case 'operational': return CheckCircle;
      case 'warning': return AlertTriangle;
      case 'maintenance': return Clock;
      case 'down': return AlertTriangle;
      default: return Settings;
    }
  };

  const operationalCount = equipment.filter(e => e.status === 'operational').length;
  const warningCount = equipment.filter(e => e.status === 'warning').length;
  const maintenanceCount = equipment.filter(e => e.status === 'maintenance').length;
  const downCount = equipment.filter(e => e.status === 'down').length;
  const avgEfficiency = equipment.reduce((sum, e) => sum + e.efficiency, 0) / equipment.length;

  // Equipment efficiency chart data
  const getEfficiencyChartData = (): ChartSeries[] => {
    const data = equipment.map(item => ({
      x: item.name,
      y: item.efficiency,
      label: `${item.name}: ${item.efficiency}%`
    }));

    return [
      {
        id: 'equipment-efficiency',
        name: t('equipment.efficiency'),
        type: 'bar',
        color: '#16a34a',
        data
      }
    ];
  };

  // Status distribution chart
  const getStatusDistributionChartData = (): ChartSeries[] => {
    const statusData = [
      { x: t('equipment.status.operational'), y: operationalCount, label: `${operationalCount} ${t('equipment.status.operational')}` },
      { x: t('equipment.status.warning'), y: warningCount, label: `${warningCount} ${t('equipment.status.warning')}` },
      { x: t('equipment.status.maintenance'), y: maintenanceCount, label: `${maintenanceCount} ${t('equipment.status.maintenance')}` },
      { x: t('equipment.status.down'), y: downCount, label: `${downCount} ${t('equipment.status.down')}` }
    ].filter(item => item.y > 0);

    return [
      {
        id: 'status-distribution',
        name: t('equipment.status.distribution'),
        type: 'doughnut',
        color: '#3b82f6',
        data: statusData
      }
    ];
  };

  return (
    <AnalyticsWidget
      title={t('equipment.title')}
      subtitle={t('equipment.subtitle')}
      icon={Settings}
      actions={
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            <Clock className="w-4 h-4 mr-1" />
            {t('equipment.actions.schedule_maintenance')}
          </Button>
          <Button variant="primary" size="sm">
            <Zap className="w-4 h-4 mr-1" />
            {t('actions.optimize')}
          </Button>
        </div>
      }
    >
      <div className="space-y-6">
        {/* Equipment Overview Stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <CheckCircle className="w-8 h-8 mx-auto text-green-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{operationalCount}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.stats.operational')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <AlertTriangle className="w-8 h-8 mx-auto text-orange-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{warningCount}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.stats.needs_attention')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="w-8 h-8 mx-auto bg-blue-100 dark:bg-blue-900/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-blue-600 font-bold text-lg">{avgEfficiency.toFixed(0)}%</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{avgEfficiency.toFixed(1)}%</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.stats.avg_efficiency')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <AlertTriangle className="w-8 h-8 mx-auto text-red-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">
              {equipment.reduce((sum, e) => sum + e.alertCount, 0)}
            </p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.stats.alerts')}</p>
          </div>
        </div>

        {/* Equipment List */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Settings className="w-4 h-4 mr-2" />
            {t('equipment.status.equipment_list')} ({equipment.length})
          </h4>
          <div className="space-y-3">
            {equipment.map((item) => {
              const StatusIcon = getStatusIcon(item.status);
              return (
                <div key={item.id} className="p-4 bg-[var(--bg-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <StatusIcon className={`w-5 h-5 ${getStatusColor(item.status)}`} />
                      <div>
                        <p className="font-medium text-[var(--text-primary)]">{item.name}</p>
                        <div className="flex items-center space-x-4 text-xs text-[var(--text-secondary)]">
                          <span>{t('equipment.efficiency')}: {item.efficiency}%</span>
                          <span>{t('equipment.uptime')}: {item.uptime}%</span>
                          {item.temperature && (
                            <span>{t('equipment.temperature')}: {item.temperature}°C</span>
                          )}
                          {item.alertCount > 0 && (
                            <span className="text-red-600">{item.alertCount} {t('equipment.unread_alerts')}</span>
                          )}
                        </div>
                      </div>
                    </div>
                    <Badge variant={getStatusBadgeVariant(item.status)}>
                      {t(`equipment.status.${item.status}`)}
                    </Badge>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Equipment Charts */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Efficiency Chart */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('equipment.efficiency')} {t('stats.by_equipment')}
            </h4>
            <AnalyticsChart
              series={getEfficiencyChartData()}
              height={200}
              showLegend={false}
              showGrid={true}
            />
          </div>

          {/* Status Distribution */}
          <div>
            <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
              {t('equipment.status.distribution')}
            </h4>
            <AnalyticsChart
              series={getStatusDistributionChartData()}
              height={200}
              showLegend={true}
              showGrid={false}
            />
          </div>
        </div>

        {/* Maintenance Alerts */}
        {equipment.some(e => e.alertCount > 0 || e.status === 'maintenance') && (
          <div className="p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
            <div className="flex items-start space-x-2">
              <AlertTriangle className="w-5 h-5 text-orange-600 mt-0.5" />
              <div>
                <p className="text-sm font-medium text-orange-600">
                  {t('equipment.alerts.maintenance_required')}
                </p>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {equipment.filter(e => e.status === 'maintenance').length} {t('equipment.alerts.equipment_in_maintenance')},
                  {equipment.reduce((sum, e) => sum + e.alertCount, 0)} {t('equipment.alerts.active_alerts')}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
    </AnalyticsWidget>
  );
};