import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { StatsGrid } from '../../ui/Stats';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import {
  Euro,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  Target,
  Clock,
  Activity,
  Zap
} from 'lucide-react';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useProductionDashboard } from '../../../api';

export interface ProductionCostData {
  totalCost: number;
  laborCost: number;
  materialCost: number;
  overheadCost: number;
  energyCost: number;
  costPerUnit: number;
  budget: number;
  variance: number;
  trend: {
    direction: 'up' | 'down' | 'stable';
    percentage: number;
  };
}

export interface ProductionCostMonitorProps {
  className?: string;
  data?: ProductionCostData;
  onViewDetails?: () => void;
  onOptimize?: () => void;
}

const ProductionCostMonitor: React.FC<ProductionCostMonitorProps> = ({
  className,
  data,
  onViewDetails,
  onOptimize
}) => {
  const { t } = useTranslation();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

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

  const costData = useMemo((): ProductionCostData => {
    if (data) return data;

    // Calculate from dashboard data if available
    if (dashboardData) {
      const mockData: ProductionCostData = {
        totalCost: 2840.50,
        laborCost: 1200.00,
        materialCost: 1450.00,
        overheadCost: 190.50,
        energyCost: 95.25,
        costPerUnit: 14.20,
        budget: 3000.00,
        variance: -159.50,
        trend: {
          direction: 'down',
          percentage: 5.3
        }
      };
      return mockData;
    }

    // Default mock data
    return {
      totalCost: 2840.50,
      laborCost: 1200.00,
      materialCost: 1450.00,
      overheadCost: 190.50,
      energyCost: 95.25,
      costPerUnit: 14.20,
      budget: 3000.00,
      variance: -159.50,
      trend: {
        direction: 'down',
        percentage: 5.3
      }
    };
  }, [data, dashboardData]);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('es-ES', {
      style: 'currency',
      currency: 'EUR',
      minimumFractionDigits: 2
    }).format(amount);
  };

  const getVarianceColor = (variance: number) => {
    if (variance > 0) return 'text-red-600';
    if (variance < -50) return 'text-green-600';
    return 'text-yellow-600';
  };

  const getBudgetStatus = () => {
    const percentage = (costData.totalCost / costData.budget) * 100;
    if (percentage > 100) return { color: 'error', label: t('production.cost.over_budget', 'Over Budget') };
    if (percentage > 90) return { color: 'warning', label: t('production.cost.near_budget', 'Near Budget') };
    return { color: 'success', label: t('production.cost.on_budget', 'On Budget') };
  };

  const budgetStatus = getBudgetStatus();

  if (isLoading) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">
            {t('production.cost.title', 'Production Cost Monitor')}
          </h3>
        </CardHeader>
        <CardBody>
          <div className="animate-pulse space-y-4">
            <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
            <div className="grid grid-cols-2 gap-4">
              <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('production.cost.error', 'Error loading cost data')}
          </p>
        </CardBody>
      </Card>
    );
  }

  const costStats = [
    {
      title: t('production.cost.total_cost', 'Total Cost'),
      value: formatCurrency(costData.totalCost),
      icon: Euro,
      variant: budgetStatus.color as 'success' | 'warning' | 'error',
      trend: {
        value: costData.trend.percentage,
        direction: costData.trend.direction === 'up' ? 'up' as const : 'down' as const,
        label: t('production.cost.vs_yesterday', 'vs yesterday')
      },
      subtitle: `${formatCurrency(Math.abs(costData.variance))} ${costData.variance > 0 ? t('common.over', 'over') : t('common.under', 'under')} ${t('common.budget', 'budget')}`
    },
    {
      title: t('production.cost.cost_per_unit', 'Cost per Unit'),
      value: formatCurrency(costData.costPerUnit),
      icon: Target,
      variant: 'info' as const,
      subtitle: t('production.cost.average_today', 'Average today')
    }
  ];

  const costBreakdown = [
    {
      label: t('production.cost.labor', 'Labor'),
      amount: costData.laborCost,
      percentage: (costData.laborCost / costData.totalCost) * 100,
      icon: Clock,
      color: 'bg-blue-500'
    },
    {
      label: t('production.cost.materials', 'Materials'),
      amount: costData.materialCost,
      percentage: (costData.materialCost / costData.totalCost) * 100,
      icon: Activity,
      color: 'bg-green-500'
    },
    {
      label: t('production.cost.overhead', 'Overhead'),
      amount: costData.overheadCost,
      percentage: (costData.overheadCost / costData.totalCost) * 100,
      icon: Euro,
      color: 'bg-orange-500'
    },
    {
      label: t('production.cost.energy', 'Energy'),
      amount: costData.energyCost,
      percentage: (costData.energyCost / costData.totalCost) * 100,
      icon: Zap,
      color: 'bg-yellow-500'
    }
  ];

  return (
    <Card className={className}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-[var(--text-primary)]">
              {t('production.cost.title', 'Production Cost Monitor')}
            </h3>
            <p className="text-sm text-[var(--text-secondary)]">
              {t('production.cost.subtitle', 'Track and optimize production costs')}
            </p>
          </div>
          <Badge variant={budgetStatus.color as any}>
            {budgetStatus.label}
          </Badge>
        </div>
      </CardHeader>

      <CardBody className="space-y-6">
        {/* Key Metrics */}
        <StatsGrid
          stats={costStats}
          columns={2}
          gap="md"
        />

        {/* Cost Breakdown */}
        <div>
          <h4 className="text-sm font-medium text-[var(--text-primary)] mb-4">
            {t('production.cost.breakdown', 'Cost Breakdown')}
          </h4>
          <div className="space-y-3">
            {costBreakdown.map((item, index) => {
              const Icon = item.icon;
              return (
                <div key={index} className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <div className={`w-3 h-3 rounded-full ${item.color}`}></div>
                    <Icon className="w-4 h-4 text-[var(--text-tertiary)]" />
                    <span className="text-sm text-[var(--text-primary)]">
                      {item.label}
                    </span>
                  </div>
                  <div className="flex items-center space-x-3">
                    <span className="text-sm font-medium text-[var(--text-primary)]">
                      {formatCurrency(item.amount)}
                    </span>
                    <span className="text-xs text-[var(--text-tertiary)] w-10 text-right">
                      {item.percentage.toFixed(1)}%
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Budget Progress */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-[var(--text-primary)]">
              {t('production.cost.budget_usage', 'Budget Usage')}
            </span>
            <span className="text-sm text-[var(--text-secondary)]">
              {formatCurrency(costData.totalCost)} / {formatCurrency(costData.budget)}
            </span>
          </div>
          <div className="w-full bg-[var(--bg-secondary)] rounded-full h-2">
            <div
              className={`h-2 rounded-full transition-all duration-300 ${
                costData.totalCost > costData.budget
                  ? 'bg-red-500'
                  : costData.totalCost > costData.budget * 0.9
                  ? 'bg-yellow-500'
                  : 'bg-green-500'
              }`}
              style={{
                width: `${Math.min(100, (costData.totalCost / costData.budget) * 100)}%`
              }}
            ></div>
          </div>
          <div className="flex items-center justify-between mt-2">
            <span className={`text-xs font-medium ${getVarianceColor(costData.variance)}`}>
              {costData.variance > 0 ? '+' : ''}{formatCurrency(costData.variance)}
            </span>
            <span className="text-xs text-[var(--text-tertiary)]">
              {((costData.totalCost / costData.budget) * 100).toFixed(1)}% {t('common.used', 'used')}
            </span>
          </div>
        </div>

        {/* Actions */}
        <div className="flex space-x-3 pt-4 border-t border-[var(--border-primary)]">
          <Button
            variant="outline"
            size="sm"
            onClick={onViewDetails}
            className="flex-1"
          >
            {t('production.cost.view_details', 'View Details')}
          </Button>
          <Button
            variant="primary"
            size="sm"
            onClick={onOptimize}
            className="flex-1"
          >
            {t('production.cost.optimize', 'Optimize Costs')}
          </Button>
        </div>
      </CardBody>
    </Card>
  );
};

export default ProductionCostMonitor;