import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import {
  Settings,
  AlertTriangle,
  CheckCircle,
  Clock,
  Thermometer,
  Activity,
  Wrench,
  Zap,
  Calendar,
  TrendingUp
} from 'lucide-react';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useProductionDashboard } from '../../../api';

export interface EquipmentStatus {
  id: string;
  name: string;
  type: 'oven' | 'mixer' | 'proofer' | 'freezer' | 'packaging';
  status: 'operational' | 'maintenance' | 'down' | 'warning';
  location: string;
  temperature?: number;
  targetTemperature?: number;
  efficiency: number;
  uptime: number;
  lastMaintenance: string;
  nextMaintenance: string;
  alerts: string[];
  energyUsage: number;
  utilizationToday: number;
}

export interface EquipmentStatusWidgetProps {
  className?: string;
  equipment?: EquipmentStatus[];
  onViewEquipment?: (equipmentId: string) => void;
  onScheduleMaintenance?: (equipmentId: string) => void;
  onViewAll?: () => void;
}

const EquipmentStatusWidget: React.FC<EquipmentStatusWidgetProps> = ({
  className,
  equipment,
  onViewEquipment,
  onScheduleMaintenance,
  onViewAll
}) => {
  const { t } = useTranslation();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const {
    data: dashboardData,
    isLoading,
    error
  } = useProductionDashboard(tenantId);

  const equipmentData = useMemo((): EquipmentStatus[] => {
    if (equipment) return equipment;

    // Mock data for demonstration
    return [
      {
        id: '1',
        name: 'Horno Principal #1',
        type: 'oven',
        status: 'operational',
        location: 'Área de Horneado',
        temperature: 220,
        targetTemperature: 220,
        efficiency: 92,
        uptime: 98.5,
        lastMaintenance: '2024-01-15',
        nextMaintenance: '2024-03-15',
        alerts: [],
        energyUsage: 45.2,
        utilizationToday: 87
      },
      {
        id: '2',
        name: 'Batidora Industrial #2',
        type: 'mixer',
        status: 'warning',
        location: 'Área de Preparación',
        efficiency: 88,
        uptime: 94.2,
        lastMaintenance: '2024-01-20',
        nextMaintenance: '2024-02-20',
        alerts: ['Vibración inusual detectada', 'Revisar correas'],
        energyUsage: 12.8,
        utilizationToday: 76
      },
      {
        id: '3',
        name: 'Cámara de Fermentación #1',
        type: 'proofer',
        status: 'maintenance',
        location: 'Área de Fermentación',
        temperature: 32,
        targetTemperature: 35,
        efficiency: 0,
        uptime: 85.1,
        lastMaintenance: '2024-01-23',
        nextMaintenance: '2024-01-24',
        alerts: ['En mantenimiento programado'],
        energyUsage: 0,
        utilizationToday: 0
      },
      {
        id: '4',
        name: 'Congelador Rápido',
        type: 'freezer',
        status: 'operational',
        location: 'Área de Congelado',
        temperature: -18,
        targetTemperature: -18,
        efficiency: 95,
        uptime: 99.2,
        lastMaintenance: '2024-01-10',
        nextMaintenance: '2024-04-10',
        alerts: [],
        energyUsage: 23.5,
        utilizationToday: 65
      }
    ];
  }, [equipment]);

  const getStatusConfig = (status: EquipmentStatus['status']) => {
    const configs = {
      operational: {
        color: 'success' as const,
        icon: CheckCircle,
        label: t('equipment.status.operational', 'Operational')
      },
      warning: {
        color: 'warning' as const,
        icon: AlertTriangle,
        label: t('equipment.status.warning', 'Warning')
      },
      maintenance: {
        color: 'info' as const,
        icon: Wrench,
        label: t('equipment.status.maintenance', 'Maintenance')
      },
      down: {
        color: 'error' as const,
        icon: AlertTriangle,
        label: t('equipment.status.down', 'Down')
      }
    };
    return configs[status];
  };

  const getEquipmentIcon = (type: EquipmentStatus['type']) => {
    const icons = {
      oven: Thermometer,
      mixer: Activity,
      proofer: Settings,
      freezer: Zap,
      packaging: Settings
    };
    return icons[type] || Settings;
  };

  const summary = useMemo(() => {
    const total = equipmentData.length;
    const operational = equipmentData.filter(e => e.status === 'operational').length;
    const warning = equipmentData.filter(e => e.status === 'warning').length;
    const maintenance = equipmentData.filter(e => e.status === 'maintenance').length;
    const down = equipmentData.filter(e => e.status === 'down').length;
    const avgEfficiency = equipmentData.reduce((sum, e) => sum + e.efficiency, 0) / total;
    const avgUptime = equipmentData.reduce((sum, e) => sum + e.uptime, 0) / total;
    const totalEnergyUsage = equipmentData.reduce((sum, e) => sum + e.energyUsage, 0);

    return {
      total,
      operational,
      warning,
      maintenance,
      down,
      avgEfficiency,
      avgUptime,
      totalEnergyUsage
    };
  }, [equipmentData]);

  if (isLoading) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">
            {t('equipment.title', 'Equipment Status')}
          </h3>
        </CardHeader>
        <CardBody>
          <div className="animate-pulse space-y-4">
            <div className="grid grid-cols-3 gap-4">
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
            </div>
            <div className="space-y-3">
              <div className="h-16 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-16 bg-[var(--bg-secondary)] rounded"></div>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={className}>
        <CardBody className="text-center py-8">
          <AlertTriangle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-[var(--text-secondary)]">
            {t('equipment.error', 'Error loading equipment data')}
          </p>
        </CardBody>
      </Card>
    );
  }

  return (
    <Card className={className}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-[var(--text-primary)]">
              {t('equipment.title', 'Equipment Status')}
            </h3>
            <p className="text-sm text-[var(--text-secondary)]">
              {t('equipment.subtitle', 'Monitor equipment health and performance')}
            </p>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={onViewAll}
          >
            {t('common.view_all', 'View All')}
          </Button>
        </div>
      </CardHeader>

      <CardBody className="space-y-6">
        {/* Summary Stats */}
        <div className="grid grid-cols-3 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {summary.operational}
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('equipment.operational', 'Operational')}
            </div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-orange-600">
              {summary.warning + summary.maintenance}
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('equipment.needs_attention', 'Needs Attention')}
            </div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-[var(--color-primary)]">
              {summary.avgEfficiency.toFixed(1)}%
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('equipment.efficiency', 'Efficiency')}
            </div>
          </div>
        </div>

        {/* Equipment List */}
        <div className="space-y-3">
          {equipmentData.slice(0, 4).map((item) => {
            const statusConfig = getStatusConfig(item.status);
            const EquipmentIcon = getEquipmentIcon(item.type);
            const StatusIcon = statusConfig.icon;

            return (
              <div
                key={item.id}
                className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors cursor-pointer"
                onClick={() => onViewEquipment?.(item.id)}
              >
                <div className="flex items-center space-x-3">
                  <div className="flex items-center space-x-2">
                    <EquipmentIcon className="w-5 h-5 text-[var(--text-tertiary)]" />
                    <StatusIcon className={`w-4 h-4 ${
                      item.status === 'operational' ? 'text-green-500' :
                      item.status === 'warning' ? 'text-orange-500' :
                      item.status === 'maintenance' ? 'text-blue-500' :
                      'text-red-500'
                    }`} />
                  </div>
                  <div>
                    <div className="font-medium text-[var(--text-primary)] text-sm">
                      {item.name}
                    </div>
                    <div className="text-xs text-[var(--text-secondary)]">
                      {item.location}
                      {item.temperature && (
                        <span className="ml-2">
                          {item.temperature}Â°C
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <div className="text-right">
                    <div className="text-sm font-medium text-[var(--text-primary)]">
                      {item.efficiency}%
                    </div>
                    <div className="text-xs text-[var(--text-secondary)]">
                      {t('equipment.efficiency', 'Efficiency')}
                    </div>
                  </div>
                  <Badge variant={statusConfig.color}>
                    {statusConfig.label}
                  </Badge>
                </div>
              </div>
            );
          })}
        </div>

        {/* Key Metrics */}
        <div className="grid grid-cols-2 gap-4 pt-4 border-t border-[var(--border-primary)]">
          <div className="text-center">
            <div className="flex items-center justify-center space-x-2 mb-1">
              <TrendingUp className="w-4 h-4 text-[var(--color-primary)]" />
              <span className="text-lg font-bold text-[var(--text-primary)]">
                {summary.avgUptime.toFixed(1)}%
              </span>
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('equipment.uptime', 'Average Uptime')}
            </div>
          </div>
          <div className="text-center">
            <div className="flex items-center justify-center space-x-2 mb-1">
              <Zap className="w-4 h-4 text-yellow-500" />
              <span className="text-lg font-bold text-[var(--text-primary)]">
                {summary.totalEnergyUsage.toFixed(1)} kW
              </span>
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('equipment.energy_usage', 'Energy Usage')}
            </div>
          </div>
        </div>

        {/* Alerts */}
        {equipmentData.some(e => e.alerts.length > 0) && (
          <div className="space-y-2">
            <h4 className="text-sm font-medium text-[var(--text-primary)]">
              {t('equipment.alerts', 'Recent Alerts')}
            </h4>
            {equipmentData
              .filter(e => e.alerts.length > 0)
              .slice(0, 3)
              .map((item) => (
                <div key={item.id} className="flex items-start space-x-2 p-2 bg-orange-50 dark:bg-orange-900/20 rounded border-l-2 border-orange-500">
                  <AlertTriangle className="w-4 h-4 text-orange-500 mt-0.5 flex-shrink-0" />
                  <div>
                    <div className="text-sm font-medium text-[var(--text-primary)]">
                      {item.name}
                    </div>
                    <div className="text-xs text-[var(--text-secondary)]">
                      {item.alerts[0]}
                    </div>
                  </div>
                </div>
              ))}
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default EquipmentStatusWidget;