import React from 'react';
import { useTranslation } from 'react-i18next';
import { BarChart3, TrendingUp, AlertTriangle, Zap } from 'lucide-react';
import { AnalyticsWidget } from '../AnalyticsWidget';
import { AnalyticsChart, ChartSeries } from '../AnalyticsChart';
import { Button, ProgressBar } from '../../../../ui';
import { useProductionDashboard, useCapacityStatus } from '../../../../../api/hooks/production';
import { useCurrentTenant } from '../../../../../stores/tenant.store';

interface CapacityData {
  resource: string;
  utilization: number;
  capacity: number;
  allocated: number;
  available: number;
  type: 'oven' | 'mixer' | 'staff' | 'station';
}

export const CapacityUtilizationWidget: React.FC = () => {
  const { t } = useTranslation('production');
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const today = new Date().toISOString().split('T')[0];

  const { data: dashboard, isLoading: dashboardLoading, error: dashboardError } = useProductionDashboard(tenantId);
  const { data: capacity, isLoading: capacityLoading, error: capacityError } = useCapacityStatus(tenantId, today);

  const isLoading = dashboardLoading || capacityLoading;
  const error = dashboardError?.message || capacityError?.message;

  const overallUtilization = dashboard?.capacity_utilization || 0;

  // Mock capacity data by resource type (in real implementation, this would be processed from capacity API)
  const getCapacityByResource = (): CapacityData[] => {
    return [
      {
        resource: t('equipment.oven_capacity'),
        utilization: 89,
        capacity: 24,
        allocated: 21,
        available: 3,
        type: 'oven'
      },
      {
        resource: t('equipment.mixer_capacity'),
        utilization: 67,
        capacity: 12,
        allocated: 8,
        available: 4,
        type: 'mixer'
      },
      {
        resource: t('schedule.staff_capacity'),
        utilization: 85,
        capacity: 8,
        allocated: 7,
        available: 1,
        type: 'staff'
      },
      {
        resource: t('schedule.work_stations'),
        utilization: 75,
        capacity: 6,
        allocated: 4,
        available: 2,
        type: 'station'
      }
    ];
  };

  const capacityData = getCapacityByResource();

  // Heatmap data for hourly utilization
  const getHourlyUtilizationData = (): ChartSeries[] => {
    const hours = Array.from({ length: 12 }, (_, i) => i + 6); // 6 AM to 6 PM
    const mockData = hours.map(hour => ({
      x: `${hour}:00`,
      y: Math.max(20, Math.min(100, 50 + Math.sin(hour / 2) * 30 + Math.random() * 20)),
      label: `${hour}:00`
    }));

    return [
      {
        id: 'hourly-utilization',
        name: t('insights.hourly_utilization'),
        type: 'area',
        color: '#d97706',
        data: mockData
      }
    ];
  };

  const getUtilizationStatus = (utilization: number) => {
    if (utilization >= 95) return { color: 'text-red-600', status: 'critical', bgColor: 'bg-red-100 dark:bg-red-900/20' };
    if (utilization >= 85) return { color: 'text-orange-600', status: 'high', bgColor: 'bg-orange-100 dark:bg-orange-900/20' };
    if (utilization >= 70) return { color: 'text-green-600', status: 'optimal', bgColor: 'bg-green-100 dark:bg-green-900/20' };
    return { color: 'text-blue-600', status: 'low', bgColor: 'bg-blue-100 dark:bg-blue-900/20' };
  };

  const getResourceIcon = (type: CapacityData['type']) => {
    switch (type) {
      case 'oven': return '🔥';
      case 'mixer': return '🥄';
      case 'staff': return '👥';
      case 'station': return '🏭';
      default: return '📊';
    }
  };

  const getProgressBarVariant = (utilization: number) => {
    if (utilization >= 95) return 'error';
    if (utilization >= 85) return 'warning';
    if (utilization >= 70) return 'success';
    return 'info';
  };

  const overallStatus = getUtilizationStatus(overallUtilization);

  return (
    <AnalyticsWidget
      title={t('stats.capacity_utilization')}
      subtitle={t('insights.resource_allocation_efficiency')}
      icon={BarChart3}
      loading={isLoading}
      error={error}
      actions={
        <Button variant="outline" size="sm">
          <Zap className="w-4 h-4 mr-1" />
          {t('actions.optimize')}
        </Button>
      }
    >
      <div className="space-y-4">
        {/* Overall Utilization */}
        <div className="text-center">
          <div className="flex items-center justify-center space-x-2 mb-2">
            <BarChart3 className={`w-6 h-6 ${overallStatus.color}`} />
            <span className="text-3xl font-bold text-[var(--text-primary)]">
              {overallUtilization.toFixed(1)}%
            </span>
          </div>
          <div className={`inline-flex items-center space-x-2 px-3 py-1 rounded-full text-sm ${overallStatus.bgColor}`}>
            <span className={overallStatus.color}>
              {t(`status.${overallStatus.status}`)}
            </span>
          </div>
        </div>

        {/* Resource Breakdown */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
            {t('insights.resource_breakdown')}
          </h4>
          <div className="space-y-3">
            {capacityData.map((resource, index) => {
              const status = getUtilizationStatus(resource.utilization);

              return (
                <div key={index} className="p-3 bg-[var(--bg-secondary)] rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center space-x-2">
                      <span className="text-lg">{getResourceIcon(resource.type)}</span>
                      <span className="text-sm font-medium text-[var(--text-primary)]">
                        {resource.resource}
                      </span>
                    </div>
                    <span className={`text-sm font-semibold ${status.color}`}>
                      {resource.utilization}%
                    </span>
                  </div>

                  <ProgressBar
                    value={resource.utilization}
                    variant={getProgressBarVariant(resource.utilization)}
                    size="sm"
                    className="mb-2"
                  />

                  <div className="flex items-center justify-between text-xs text-[var(--text-secondary)]">
                    <span>
                      {resource.allocated}/{resource.capacity} {t('common.allocated')}
                    </span>
                    <span>
                      {resource.available} {t('common.available')}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Hourly Heatmap */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-3">
            {t('insights.hourly_utilization_pattern')}
          </h4>
          <AnalyticsChart
            series={getHourlyUtilizationData()}
            height={120}
            showLegend={false}
            showGrid={true}
          />
        </div>

        {/* Alerts & Recommendations */}
        <div className="space-y-2">
          {capacityData.some(r => r.utilization >= 95) && (
            <div className="flex items-start space-x-2 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
              <AlertTriangle className="w-4 h-4 mt-0.5 text-red-600" />
              <div>
                <p className="text-sm font-medium text-red-600">
                  {t('alerts.capacity_critical')}
                </p>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('alerts.capacity_critical_description')}
                </p>
              </div>
            </div>
          )}

          {capacityData.some(r => r.utilization >= 85 && r.utilization < 95) && (
            <div className="flex items-start space-x-2 p-3 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
              <TrendingUp className="w-4 h-4 mt-0.5 text-orange-600" />
              <div>
                <p className="text-sm font-medium text-orange-600">
                  {t('alerts.capacity_high')}
                </p>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('alerts.capacity_high_description')}
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Peak Hours Summary */}
        <div className="pt-3 border-t border-[var(--border-primary)]">
          <div className="grid grid-cols-2 gap-3 text-center text-sm">
            <div>
              <p className="font-semibold text-[var(--text-primary)]">10:00 - 12:00</p>
              <p className="text-xs text-[var(--text-secondary)]">{t('insights.peak_hours')}</p>
            </div>
            <div>
              <p className="font-semibold text-[var(--text-primary)]">14:00 - 16:00</p>
              <p className="text-xs text-[var(--text-secondary)]">{t('insights.off_peak_optimal')}</p>
            </div>
          </div>
        </div>
      </div>
    </AnalyticsWidget>
  );
};