import React from 'react';
import { useTranslation } from 'react-i18next';
import { Calendar, Clock, Users, Target, AlertCircle } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { Badge, Button } from '../../../../ui';
import { useProductionDashboard, useProductionSchedule } from '../../../../../api/hooks/production';
import { useCurrentTenant } from '../../../../../stores/tenant.store';
import { ProductionStatus } from '../../../../../api/types/production';

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

  const { data: dashboard, isLoading: dashboardLoading, error: dashboardError } = useProductionDashboard(tenantId);
  const today = new Date().toISOString().split('T')[0];
  const { data: schedule, isLoading: scheduleLoading, error: scheduleError } = useProductionSchedule(tenantId, today, today);

  const isLoading = dashboardLoading || scheduleLoading;
  const error = dashboardError?.message || scheduleError?.message;

  const todaysSchedule = schedule?.schedules?.[0];
  const plannedBatches = dashboard?.todays_production_plan || [];

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

  const getPriorityColor = (priority?: string) => {
    if (!priority) return 'text-gray-600';

    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 formatTime = (timeString: string) => {
    return new Date(timeString).toLocaleTimeString('es-ES', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <AnalyticsWidget
      title={t('schedule.todays_summary')}
      subtitle={t('schedule.shift_hours_batches_staff')}
      icon={Calendar}
      loading={isLoading}
      error={error}
      actions={
        <Button variant="outline" size="sm">
          <Target className="w-4 h-4 mr-1" />
          {t('actions.optimize')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Schedule Overview */}
        {todaysSchedule && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="text-center">
              <Clock className="w-5 h-5 text-[var(--color-primary)] mx-auto mb-1" />
              <p className="text-sm text-[var(--text-secondary)]">{t('schedule.shift_hours')}</p>
              <p className="font-semibold text-[var(--text-primary)]">
                {formatTime(todaysSchedule.shift_start)} - {formatTime(todaysSchedule.shift_end)}
              </p>
            </div>
            <div className="text-center">
              <Target className="w-5 h-5 text-[var(--color-primary)] mx-auto mb-1" />
              <p className="text-sm text-[var(--text-secondary)]">{t('stats.planned_batches')}</p>
              <p className="font-semibold text-[var(--text-primary)]">{todaysSchedule.total_batches_planned}</p>
            </div>
            <div className="text-center">
              <Users className="w-5 h-5 text-[var(--color-primary)] mx-auto mb-1" />
              <p className="text-sm text-[var(--text-secondary)]">{t('schedule.staff_count')}</p>
              <p className="font-semibold text-[var(--text-primary)]">{todaysSchedule.staff_count}</p>
            </div>
            <div className="text-center">
              <AlertCircle className="w-5 h-5 text-[var(--color-primary)] mx-auto mb-1" />
              <p className="text-sm text-[var(--text-secondary)]">{t('schedule.capacity_utilization')}</p>
              <p className="font-semibold text-[var(--text-primary)]">
                {todaysSchedule.utilization_percentage?.toFixed(1) || 0}%
              </p>
            </div>
          </div>
        )}

        {/* Planned Batches */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3 flex items-center">
            <Target className="w-4 h-4 mr-2" />
            {t('schedule.planned_batches')} ({plannedBatches.length})
          </h4>

          {plannedBatches.length === 0 ? (
            <div className="text-center py-6 text-[var(--text-secondary)]">
              <Calendar className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p className="text-sm">{t('messages.no_batches_planned')}</p>
            </div>
          ) : (
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {plannedBatches.map((batch, index) => (
                <div
                  key={batch.batch_id || index}
                  className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-2 mb-1">
                      <p className="font-medium text-[var(--text-primary)] truncate">
                        {batch.product_name}
                      </p>
                      {batch.priority && (
                        <span className={`text-xs font-medium ${getPriorityColor(batch.priority)}`}>
                          {t(`priority.${batch.priority.toLowerCase()}`)}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-[var(--text-secondary)]">
                      {t('batch.planned_quantity')}: {batch.planned_quantity} {t('common.units')}
                    </p>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant={getStatusBadgeVariant(batch.status)}>
                      {batch.status ? t(`status.${batch.status.toLowerCase()}`) : t('status.unknown')}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Schedule Status */}
        {todaysSchedule && (
          <div className="flex items-center justify-between pt-3 border-t border-[var(--border-primary)]">
            <div className="flex items-center space-x-2 text-sm">
              <div className={`w-2 h-2 rounded-full ${todaysSchedule.is_active ? 'bg-green-500' : 'bg-gray-400'}`} />
              <span className="text-[var(--text-secondary)]">
                {todaysSchedule.is_active ? t('schedule.active') : t('schedule.inactive')}
              </span>
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {todaysSchedule.is_finalized ? (
                <span className="text-green-600">{t('schedule.finalized')}</span>
              ) : (
                <span className="text-orange-600">{t('schedule.draft')}</span>
              )}
            </div>
          </div>
        )}
      </div>
    </AnalyticsWidget>
  );
};