import React from 'react';
import { useTranslation } from 'react-i18next';
import { Activity, Clock, AlertCircle, CheckCircle, Play, Pause, Zap } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { Badge, ProgressBar, Button } from '../../../../ui';
import { useActiveBatches } from '../../../../../api/hooks/production';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { ProductionStatus } from '../../../../../api/types/production';

export const LiveBatchTrackerWidget: React.FC = () => {
  const { t } = useTranslation('production');
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const { data: batchesData, isLoading, error } = useActiveBatches(tenantId);
  const batches = batchesData?.batches || [];

  const getStatusIcon = (status: ProductionStatus) => {
    switch (status) {
      case ProductionStatus.COMPLETED:
        return CheckCircle;
      case ProductionStatus.IN_PROGRESS:
        return Play;
      case ProductionStatus.ON_HOLD:
        return Pause;
      case ProductionStatus.FAILED:
        return AlertCircle;
      default:
        return Clock;
    }
  };

  const getStatusBadgeVariant = (status: ProductionStatus) => {
    switch (status) {
      case ProductionStatus.COMPLETED:
        return 'success';
      case ProductionStatus.IN_PROGRESS:
        return 'info';
      case ProductionStatus.PENDING:
        return 'warning';
      case ProductionStatus.ON_HOLD:
        return 'warning';
      case ProductionStatus.CANCELLED:
      case ProductionStatus.FAILED:
        return 'error';
      default:
        return 'default';
    }
  };

  const calculateProgress = (batch: any) => {
    if (batch.status === ProductionStatus.COMPLETED) return 100;
    if (batch.status === ProductionStatus.PENDING) return 0;

    if (batch.actual_start_time && batch.planned_duration_minutes) {
      const startTime = new Date(batch.actual_start_time).getTime();
      const now = new Date().getTime();
      const elapsed = (now - startTime) / (1000 * 60); // minutes
      const progress = Math.min((elapsed / batch.planned_duration_minutes) * 100, 100);
      return Math.round(progress);
    }

    return 25; // Default for in-progress without timing info
  };

  const calculateETA = (batch: any) => {
    if (batch.status === ProductionStatus.COMPLETED) return null;
    if (!batch.actual_start_time || !batch.planned_duration_minutes) return null;

    const startTime = new Date(batch.actual_start_time).getTime();
    const eta = new Date(startTime + batch.planned_duration_minutes * 60 * 1000);
    const now = new Date();

    if (eta < now) {
      const delay = Math.round((now.getTime() - eta.getTime()) / (1000 * 60));
      return `${delay}m ${t('schedule.delayed')}`;
    }

    return eta.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
  };

  const getProgressBarVariant = (status: ProductionStatus, progress: number) => {
    if (status === ProductionStatus.COMPLETED) return 'success';
    if (status === ProductionStatus.FAILED || status === ProductionStatus.CANCELLED) return 'error';
    if (progress > 90) return 'warning';
    return 'info';
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'URGENT':
        return 'text-[var(--color-error)]';
      case 'HIGH':
        return 'text-[var(--color-warning)]';
      case 'MEDIUM':
        return 'text-[var(--color-info)]';
      default:
        return 'text-[var(--text-secondary)]';
    }
  };

  return (
    <AnalyticsWidget
      title={t('tracker.live_batch_tracker')}
      subtitle={t('tracker.current_batches_status_progress')}
      icon={Activity}
      loading={isLoading}
      error={error?.message}
      actions={
        <Button variant="outline" size="sm">
          <Activity className="w-4 h-4 mr-1" />
          {t('actions.refresh')}
        </Button>
      }
    >
      <div className="space-y-3">
        {batches.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)]">
            <Activity className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
              {t('messages.no_active_batches')}
            </h3>
            <p className="text-sm">{t('messages.no_active_batches_description')}</p>
          </div>
        ) : (
          <div className="space-y-3 max-h-96 overflow-y-auto pr-1">
            {batches.map((batch) => {
              const StatusIcon = getStatusIcon(batch.status);
              const progress = calculateProgress(batch);
              const eta = calculateETA(batch);

              return (
                <div
                  key={batch.id}
                  className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] hover:border-[var(--border-focus)] hover:shadow-md transition-all duration-200"
                >
                  {/* Header */}
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start space-x-3 flex-1">
                      <div className="w-8 h-8 bg-[var(--color-primary)]/10 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
                        <StatusIcon className="w-4 h-4 text-[var(--color-primary)]" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="font-semibold text-[var(--text-primary)] mb-1 truncate">
                          {batch.product_name}
                        </h4>
                        <p className="text-sm text-[var(--text-secondary)] mb-1">
                          {t('batch.batch_number')}: {batch.batch_number}
                        </p>
                        <div className="flex items-center space-x-4 text-xs text-[var(--text-tertiary)]">
                          <span>{batch.planned_quantity} {t('common.units')}</span>
                          {batch.actual_quantity && (
                            <span>
                              {t('batch.actual')}: {batch.actual_quantity} {t('common.units')}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <Badge variant={getStatusBadgeVariant(batch.status)} className="flex-shrink-0">
                      {t(`status.${batch.status.toLowerCase()}`)}
                    </Badge>
                  </div>

                  {/* Progress Bar */}
                  {batch.status !== ProductionStatus.PENDING && (
                    <div className="mb-3">
                      <div className="flex items-center justify-between mb-1.5">
                        <span className="text-xs font-medium text-[var(--text-secondary)]">
                          {t('tracker.progress')}
                        </span>
                        <span className="text-xs font-semibold text-[var(--text-primary)]">
                          {progress}%
                        </span>
                      </div>
                      <ProgressBar
                        value={progress}
                        variant={getProgressBarVariant(batch.status, progress)}
                        size="sm"
                      />
                    </div>
                  )}

                  {/* Details */}
                  <div className="flex items-center justify-between text-xs flex-wrap gap-2">
                    <div className="flex items-center space-x-3">
                      {batch.priority && (
                        <span className={`font-semibold ${getPriorityColor(batch.priority)}`}>
                          {t(`priority.${batch.priority.toLowerCase()}`)}
                        </span>
                      )}
                      {batch.is_rush_order && (
                        <span className="text-[var(--color-error)] font-semibold flex items-center">
                          <Zap className="w-3 h-3 mr-1" />
                          {t('batch.rush_order')}
                        </span>
                      )}
                    </div>
                    <div className="flex items-center space-x-1.5 text-[var(--text-secondary)]">
                      <Clock className="w-3.5 h-3.5" />
                      <span>
                        {eta ? (
                          <span className={eta.includes('delayed') ? 'text-[var(--color-error)] font-medium' : 'font-medium'}>
                            ETA: {eta}
                          </span>
                        ) : (
                          <span className="font-medium">{t('tracker.pending_start')}</span>
                        )}
                      </span>
                    </div>
                  </div>

                  {/* Equipment & Staff */}
                  {(batch.equipment_used?.length > 0 || batch.staff_assigned?.length > 0) && (
                    <div className="mt-3 pt-3 border-t border-[var(--border-secondary)] text-xs">
                      {batch.equipment_used?.length > 0 && (
                        <div className="mb-1.5 flex items-start">
                          <span className="text-[var(--text-secondary)] font-medium mr-2">{t('batch.equipment')}:</span>
                          <span className="text-[var(--text-tertiary)] flex-1">{batch.equipment_used.join(', ')}</span>
                        </div>
                      )}
                      {batch.staff_assigned?.length > 0 && (
                        <div className="flex items-center">
                          <span className="text-[var(--text-secondary)] font-medium mr-2">{t('batch.staff')}:</span>
                          <span className="text-[var(--text-tertiary)]">
                            {batch.staff_assigned.length} {t('common.assigned')}
                          </span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}

        {/* Summary */}
        {batches.length > 0 && (
          <div className="pt-4 mt-2 border-t border-[var(--border-primary)]">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center text-xs">
              <div className="p-3 bg-[var(--color-success)]/10 rounded-lg border border-[var(--color-success)]/20">
                <p className="text-2xl font-bold text-[var(--color-success)] mb-1">
                  {batches.filter(b => b.status === ProductionStatus.COMPLETED).length}
                </p>
                <p className="text-[var(--text-secondary)] font-medium">{t('status.completed')}</p>
              </div>
              <div className="p-3 bg-[var(--color-info)]/10 rounded-lg border border-[var(--color-info)]/20">
                <p className="text-2xl font-bold text-[var(--color-info)] mb-1">
                  {batches.filter(b => b.status === ProductionStatus.IN_PROGRESS).length}
                </p>
                <p className="text-[var(--text-secondary)] font-medium">{t('status.in_progress')}</p>
              </div>
              <div className="p-3 bg-[var(--color-warning)]/10 rounded-lg border border-[var(--color-warning)]/20">
                <p className="text-2xl font-bold text-[var(--color-warning)] mb-1">
                  {batches.filter(b => b.status === ProductionStatus.PENDING).length}
                </p>
                <p className="text-[var(--text-secondary)] font-medium">{t('status.pending')}</p>
              </div>
              <div className="p-3 bg-[var(--color-error)]/10 rounded-lg border border-[var(--color-error)]/20">
                <p className="text-2xl font-bold text-[var(--color-error)] mb-1">
                  {batches.filter(b => [ProductionStatus.FAILED, ProductionStatus.CANCELLED].includes(b.status)).length}
                </p>
                <p className="text-[var(--text-secondary)] font-medium">{t('tracker.issues')}</p>
              </div>
            </div>
          </div>
        )}
      </div>
    </AnalyticsWidget>
  );
};