import React from 'react';
import { useTranslation } from 'react-i18next';
import { Calendar, Clock, Wrench, AlertCircle, CheckCircle2 } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { Badge, Button } from '../../../../ui';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../../hooks/useTenantCurrency';

interface MaintenanceTask {
  id: string;
  equipmentId: string;
  equipmentName: string;
  type: 'preventive' | 'corrective' | 'inspection';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status: 'scheduled' | 'in_progress' | 'completed' | 'overdue';
  scheduledDate: string;
  completedDate?: string;
  estimatedDuration: number; // in hours
  actualDuration?: number;
  technician?: string;
  description: string;
  cost?: number;
}

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

  // Mock maintenance data - replace with real API call
  const maintenanceTasks: MaintenanceTask[] = [
    {
      id: '1',
      equipmentId: '1',
      equipmentName: 'Horno Principal',
      type: 'preventive',
      priority: 'high',
      status: 'scheduled',
      scheduledDate: '2024-01-28',
      estimatedDuration: 4,
      description: 'Limpieza profunda y calibración de temperatura',
      cost: 150
    },
    {
      id: '2',
      equipmentId: '2',
      equipmentName: 'Mezcladora A',
      type: 'corrective',
      priority: 'urgent',
      status: 'overdue',
      scheduledDate: '2024-01-25',
      estimatedDuration: 2,
      description: 'Reparación de motor y reemplazo de correas',
      cost: 280
    },
    {
      id: '3',
      equipmentId: '3',
      equipmentName: 'Cámara de Fermentación 1',
      type: 'inspection',
      priority: 'medium',
      status: 'in_progress',
      scheduledDate: '2024-01-26',
      estimatedDuration: 1,
      technician: 'Carlos López',
      description: 'Inspección rutinaria de sistemas de control',
      cost: 80
    },
    {
      id: '4',
      equipmentId: '4',
      equipmentName: 'Empaquetadora',
      type: 'preventive',
      priority: 'medium',
      status: 'completed',
      scheduledDate: '2024-01-24',
      completedDate: '2024-01-24',
      estimatedDuration: 3,
      actualDuration: 2.5,
      technician: 'Ana García',
      description: 'Mantenimiento preventivo mensual',
      cost: 120
    },
    {
      id: '5',
      equipmentId: '1',
      equipmentName: 'Horno Principal',
      type: 'inspection',
      priority: 'low',
      status: 'scheduled',
      scheduledDate: '2024-02-05',
      estimatedDuration: 0.5,
      description: 'Inspección de seguridad semanal'
    }
  ];

  const getStatusColor = (status: MaintenanceTask['status']) => {
    switch (status) {
      case 'completed': return 'text-green-600';
      case 'in_progress': return 'text-blue-600';
      case 'scheduled': return 'text-orange-600';
      case 'overdue': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  const getStatusBadgeVariant = (status: MaintenanceTask['status']) => {
    switch (status) {
      case 'completed': return 'success';
      case 'in_progress': return 'info';
      case 'scheduled': return 'warning';
      case 'overdue': return 'error';
      default: return 'default';
    }
  };

  const getPriorityColor = (priority: MaintenanceTask['priority']) => {
    switch (priority) {
      case 'urgent': return 'text-red-600';
      case 'high': return 'text-orange-600';
      case 'medium': return 'text-blue-600';
      case 'low': return 'text-gray-600';
      default: return 'text-gray-600';
    }
  };

  const getTypeIcon = (type: MaintenanceTask['type']) => {
    switch (type) {
      case 'preventive': return Calendar;
      case 'corrective': return Wrench;
      case 'inspection': return CheckCircle2;
      default: return Wrench;
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('es-ES', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  };

  const scheduledTasks = maintenanceTasks.filter(t => t.status === 'scheduled');
  const overdueTasks = maintenanceTasks.filter(t => t.status === 'overdue');
  const inProgressTasks = maintenanceTasks.filter(t => t.status === 'in_progress');
  const completedTasks = maintenanceTasks.filter(t => t.status === 'completed');

  const totalCost = maintenanceTasks.reduce((sum, task) => sum + (task.cost || 0), 0);
  const avgDuration = maintenanceTasks.reduce((sum, task) => sum + task.estimatedDuration, 0) / maintenanceTasks.length;

  return (
    <AnalyticsWidget
      title={t('equipment.maintenance.title')}
      subtitle={t('equipment.maintenance.subtitle')}
      icon={Calendar}
      actions={
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            <Calendar className="w-4 h-4 mr-1" />
            {t('equipment.actions.schedule_maintenance')}
          </Button>
          <Button variant="primary" size="sm">
            <Wrench className="w-4 h-4 mr-1" />
            {t('equipment.actions.add_task')}
          </Button>
        </div>
      }
    >
      <div className="space-y-6">
        {/* Maintenance 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">
            <Calendar className="w-8 h-8 mx-auto text-orange-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{scheduledTasks.length}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.maintenance.scheduled')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <AlertCircle className="w-8 h-8 mx-auto text-red-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{overdueTasks.length}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.maintenance.overdue')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <Clock className="w-8 h-8 mx-auto text-blue-600 mb-2" />
            <p className="text-2xl font-bold text-[var(--text-primary)]">{avgDuration.toFixed(1)}h</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.maintenance.avg_duration')}</p>
          </div>
          <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="w-8 h-8 mx-auto bg-green-100 dark:bg-green-900/20 rounded-full flex items-center justify-center mb-2">
              <span className="text-green-600 font-bold text-sm">{currencySymbol}</span>
            </div>
            <p className="text-2xl font-bold text-[var(--text-primary)]">{currencySymbol}{totalCost}</p>
            <p className="text-sm text-[var(--text-secondary)]">{t('equipment.maintenance.total_cost')}</p>
          </div>
        </div>

        {/* Priority Tasks */}
        {overdueTasks.length > 0 && (
          <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
            <div className="flex items-start space-x-2">
              <AlertCircle className="w-5 h-5 text-red-600 mt-0.5" />
              <div>
                <p className="text-sm font-medium text-red-600">
                  {t('equipment.maintenance.overdue_tasks')} ({overdueTasks.length})
                </p>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('equipment.maintenance.immediate_attention_required')}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Maintenance Tasks List */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Wrench className="w-4 h-4 mr-2" />
            {t('equipment.maintenance.tasks')} ({maintenanceTasks.length})
          </h4>
          <div className="space-y-3">
            {maintenanceTasks.map((task) => {
              const TypeIcon = getTypeIcon(task.type);
              return (
                <div key={task.id} className="p-4 bg-[var(--bg-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start space-x-3">
                      <TypeIcon className={`w-5 h-5 mt-1 ${getStatusColor(task.status)}`} />
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-1">
                          <p className="font-medium text-[var(--text-primary)]">{task.equipmentName}</p>
                          <span className={`text-xs font-medium ${getPriorityColor(task.priority)}`}>
                            {t(`priority.${task.priority}`)}
                          </span>
                        </div>
                        <p className="text-sm text-[var(--text-secondary)] mb-2">{task.description}</p>
                        <div className="flex items-center space-x-4 text-xs text-[var(--text-secondary)]">
                          <span>{t('equipment.maintenance.scheduled')}: {formatDate(task.scheduledDate)}</span>
                          <span>{t('equipment.maintenance.duration')}: {task.estimatedDuration}h</span>
                          {task.cost && <span>{t('equipment.maintenance.cost')}: {currencySymbol}{task.cost}</span>}
                          {task.technician && <span>{t('equipment.maintenance.technician')}: {task.technician}</span>}
                        </div>
                      </div>
                    </div>
                    <div className="flex flex-col items-end space-y-2">
                      <Badge variant={getStatusBadgeVariant(task.status)}>
                        {t(`equipment.maintenance.status.${task.status}`)}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {t(`equipment.maintenance.type.${task.type}`)}
                      </Badge>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Weekly Schedule Preview */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Calendar className="w-4 h-4 mr-2" />
            {t('equipment.maintenance.this_week')}
          </h4>
          <div className="grid grid-cols-7 gap-1">
            {Array.from({ length: 7 }, (_, i) => {
              const date = new Date();
              date.setDate(date.getDate() + i);
              const dateStr = date.toISOString().split('T')[0];
              const tasksForDay = maintenanceTasks.filter(task => task.scheduledDate === dateStr);

              return (
                <div key={i} className="p-2 bg-[var(--bg-secondary)] rounded text-center">
                  <p className="text-xs text-[var(--text-secondary)] mb-1">
                    {date.toLocaleDateString('es-ES', { weekday: 'short' })}
                  </p>
                  <p className="text-sm font-medium text-[var(--text-primary)]">
                    {date.getDate()}
                  </p>
                  {tasksForDay.length > 0 && (
                    <div className="w-2 h-2 bg-orange-500 rounded-full mx-auto mt-1"></div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Maintenance Insights */}
        <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
          <div className="flex items-start space-x-2">
            <CheckCircle2 className="w-5 h-5 text-blue-600 mt-0.5" />
            <div>
              <p className="text-sm font-medium text-blue-600">
                {t('equipment.maintenance.insights.title')}
              </p>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {completedTasks.length} {t('equipment.maintenance.insights.completed_this_month')},
                {scheduledTasks.length} {t('equipment.maintenance.insights.scheduled_next_week')}
              </p>
            </div>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};