import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Calculator, TrendingUp, Clock, DollarSign, ArrowRight, Sparkles, ChevronDown, ChevronUp } from 'lucide-react';
import { Card, Button } from '../ui';
import type { SubscriptionTier } from '../../api';

type DisplayContext = 'landing' | 'settings' | 'modal';

interface ROICalculatorProps {
  currentTier: SubscriptionTier;
  targetTier: SubscriptionTier;
  monthlyPrice: number;
  context?: DisplayContext;
  onUpgrade?: () => void;
  className?: string;
  defaultExpanded?: boolean;
}

interface BakeryMetrics {
  dailySales: number;
  currentWastePercentage: number;
  employees: number;
  hoursPerWeekOnManualTasks: number;
}

interface ROIResults {
  monthlySavings: number;
  wasteSavings: number;
  timeSavings: number;
  laborCostSavings: number;
  paybackPeriodDays: number;
  annualROI: number;
  breakEvenDate: string;
}

export const ROICalculator: React.FC<ROICalculatorProps> = ({
  currentTier,
  targetTier,
  monthlyPrice,
  context = 'settings',
  onUpgrade,
  className = '',
  defaultExpanded = false
}) => {
  const { t } = useTranslation('subscription');

  // Default values based on typical bakery
  const [metrics, setMetrics] = useState<BakeryMetrics>({
    dailySales: 1500,
    currentWastePercentage: 15,
    employees: 3,
    hoursPerWeekOnManualTasks: 15
  });

  const [results, setResults] = useState<ROIResults | null>(null);
  const [isExpanded, setIsExpanded] = useState(defaultExpanded || context === 'modal');

  // Calculate ROI whenever metrics change
  useEffect(() => {
    calculateROI();
  }, [metrics, monthlyPrice]);

  const calculateROI = () => {
    const {
      dailySales,
      currentWastePercentage,
      employees,
      hoursPerWeekOnManualTasks
    } = metrics;

    // Waste reduction estimates (based on actual customer data)
    // Professional tier: 15% → 8% (7 percentage points reduction)
    // Enterprise tier: 15% → 5% (10 percentage points reduction)
    const wasteReductionPercentagePoints = targetTier === 'professional' ? 7 : 10;
    const improvedWastePercentage = Math.max(
      currentWastePercentage - wasteReductionPercentagePoints,
      3 // Minimum achievable waste
    );

    // Monthly waste savings
    const monthlySales = dailySales * 30;
    const currentWasteCost = monthlySales * (currentWastePercentage / 100);
    const improvedWasteCost = monthlySales * (improvedWastePercentage / 100);
    const wasteSavings = currentWasteCost - improvedWasteCost;

    // Time savings (automation reduces manual tasks by 60-80%)
    const timeSavingPercentage = targetTier === 'professional' ? 0.6 : 0.75;
    const weeklySavedHours = hoursPerWeekOnManualTasks * timeSavingPercentage;
    const monthlySavedHours = weeklySavedHours * 4.33; // Average weeks per month

    // Labor cost savings (€15/hour average bakery labor cost)
    const laborCostPerHour = 15;
    const laborCostSavings = monthlySavedHours * laborCostPerHour;

    // Total monthly savings
    const monthlySavings = wasteSavings + laborCostSavings;

    // Payback period
    const paybackPeriodDays = Math.max(
      Math.round((monthlyPrice / monthlySavings) * 30),
      1
    );

    // Annual ROI
    const annualCost = monthlyPrice * 12;
    const annualSavings = monthlySavings * 12;
    const annualROI = ((annualSavings - annualCost) / annualCost) * 100;

    // Break-even date
    const today = new Date();
    const breakEvenDate = new Date(today);
    breakEvenDate.setDate(today.getDate() + paybackPeriodDays);

    setResults({
      monthlySavings,
      wasteSavings,
      timeSavings: weeklySavedHours,
      laborCostSavings,
      paybackPeriodDays,
      annualROI,
      breakEvenDate: breakEvenDate.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      })
    });
  };

  const handleInputChange = (field: keyof BakeryMetrics, value: string) => {
    const numValue = parseFloat(value) || 0;
    setMetrics(prev => ({ ...prev, [field]: numValue }));
  };

  const formatCurrency = (amount: number) => {
    return `€${Math.round(amount).toLocaleString()}`;
  };

  // Render compact summary for landing page
  const renderCompactSummary = () => {
    if (!results) return null;

    return (
      <div className="flex items-center justify-between p-4 bg-gradient-to-r from-emerald-50 to-green-50 dark:from-emerald-900/20 dark:to-green-900/20 border-2 border-emerald-400/40 rounded-lg">
        <div className="flex items-center gap-3">
          <Calculator className="w-8 h-8 text-emerald-600 dark:text-emerald-400" />
          <div>
            <p className="text-sm font-medium text-emerald-900 dark:text-emerald-100">
              Estimated Monthly Savings
            </p>
            <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
              {formatCurrency(results.monthlySavings)}
            </p>
          </div>
        </div>
        <div className="text-right">
          <p className="text-xs text-emerald-700 dark:text-emerald-300">Payback in</p>
          <p className="text-lg font-bold text-emerald-600 dark:text-emerald-400">
            {results.paybackPeriodDays} days
          </p>
        </div>
      </div>
    );
  };

  // Compact view for landing page - no inputs, just results
  if (context === 'landing') {
    return (
      <div className={className}>
        {renderCompactSummary()}
      </div>
    );
  }

  // Collapsible view for settings page
  const isCollapsible = context === 'settings';

  return (
    <Card className={`${isCollapsible ? 'p-4' : 'p-6'} ${className}`}>
      {/* Header */}
      <div
        className={`flex items-center justify-between ${isCollapsible ? 'mb-4 cursor-pointer' : 'mb-6'}`}
        onClick={isCollapsible ? () => setIsExpanded(!isExpanded) : undefined}
      >
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 rounded-full bg-gradient-to-br from-blue-500 to-blue-700 flex items-center justify-center">
            <Calculator className="w-6 h-6 text-white" />
          </div>
          <div>
            <h3 className="text-xl font-bold text-[var(--text-primary)]">
              ROI Calculator
            </h3>
            <p className="text-sm text-[var(--text-secondary)]">
              Calculate your savings with {targetTier.charAt(0).toUpperCase() + targetTier.slice(1)}
            </p>
          </div>
        </div>
        {isCollapsible && (
          <button className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors">
            {isExpanded ? (
              <ChevronUp className="w-6 h-6" />
            ) : (
              <ChevronDown className="w-6 h-6" />
            )}
          </button>
        )}
      </div>

      {/* Compact summary when collapsed */}
      {isCollapsible && !isExpanded && renderCompactSummary()}

      {/* Full calculator when expanded or in modal mode */}
      {(isExpanded || !isCollapsible) && (
        <>
          {/* Input Form */}
          <div className="space-y-4 mb-6">
        {/* Daily Sales */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-2">
            Average Daily Sales
          </label>
          <div className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]">€</span>
            <input
              type="number"
              value={metrics.dailySales}
              onChange={(e) => handleInputChange('dailySales', e.target.value)}
              className="w-full pl-8 pr-4 py-2 border-2 border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] focus:border-[var(--color-primary)] focus:ring-2 focus:ring-[var(--color-primary)]/20 outline-none transition-all"
              placeholder="1500"
              min="0"
              step="100"
            />
          </div>
        </div>

        {/* Current Waste */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-2">
            Current Waste Percentage
          </label>
          <div className="relative">
            <input
              type="number"
              value={metrics.currentWastePercentage}
              onChange={(e) => handleInputChange('currentWastePercentage', e.target.value)}
              className="w-full pr-8 pl-4 py-2 border-2 border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] focus:border-[var(--color-primary)] focus:ring-2 focus:ring-[var(--color-primary)]/20 outline-none transition-all"
              placeholder="15"
              min="0"
              max="100"
              step="1"
            />
            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]">%</span>
          </div>
          <p className="text-xs text-[var(--text-secondary)] mt-1">
            Industry average: 12-18%
          </p>
        </div>

        {/* Employees */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-2">
            Number of Employees
          </label>
          <input
            type="number"
            value={metrics.employees}
            onChange={(e) => handleInputChange('employees', e.target.value)}
            className="w-full px-4 py-2 border-2 border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] focus:border-[var(--color-primary)] focus:ring-2 focus:ring-[var(--color-primary)]/20 outline-none transition-all"
            placeholder="3"
            min="1"
            step="1"
          />
        </div>

        {/* Manual Tasks */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-2">
            Hours/Week on Manual Tasks
          </label>
          <input
            type="number"
            value={metrics.hoursPerWeekOnManualTasks}
            onChange={(e) => handleInputChange('hoursPerWeekOnManualTasks', e.target.value)}
            className="w-full px-4 py-2 border-2 border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] focus:border-[var(--color-primary)] focus:ring-2 focus:ring-[var(--color-primary)]/20 outline-none transition-all"
            placeholder="15"
            min="0"
            step="1"
          />
          <p className="text-xs text-[var(--text-secondary)] mt-1">
            Inventory counts, order planning, waste tracking, etc.
          </p>
        </div>
      </div>

      {/* Results */}
      {results && (
        <div className="space-y-4">
          {/* Divider */}
          <div className="border-t-2 border-[var(--border-primary)] pt-4">
            <h4 className="text-sm font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
              <Sparkles className="w-4 h-4 text-emerald-500" />
              Your Estimated Savings
            </h4>
          </div>

          {/* Monthly Savings */}
          <div className="bg-gradient-to-r from-emerald-50 to-green-50 dark:from-emerald-900/20 dark:to-green-900/20 border-2 border-emerald-400/40 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <DollarSign className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
                <span className="text-sm font-medium text-emerald-900 dark:text-emerald-100">
                  Monthly Savings
                </span>
              </div>
              <span className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                {formatCurrency(results.monthlySavings)}
              </span>
            </div>
            <div className="mt-2 space-y-1 text-xs text-emerald-700 dark:text-emerald-300">
              <div className="flex justify-between">
                <span>Waste reduction:</span>
                <span className="font-semibold">{formatCurrency(results.wasteSavings)}/mo</span>
              </div>
              <div className="flex justify-between">
                <span>Labor cost savings:</span>
                <span className="font-semibold">{formatCurrency(results.laborCostSavings)}/mo</span>
              </div>
            </div>
          </div>

          {/* Time Savings */}
          <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
            <div className="flex items-center gap-2">
              <Clock className="w-5 h-5 text-blue-600 dark:text-blue-400" />
              <span className="text-sm font-medium text-[var(--text-primary)]">
                Time Saved
              </span>
            </div>
            <span className="text-lg font-bold text-blue-600 dark:text-blue-400">
              {results.timeSavings.toFixed(1)} hours/week
            </span>
          </div>

          {/* Payback Period */}
          <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
            <div className="flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-purple-600 dark:text-purple-400" />
              <span className="text-sm font-medium text-[var(--text-primary)]">
                Payback Period
              </span>
            </div>
            <span className="text-lg font-bold text-purple-600 dark:text-purple-400">
              {results.paybackPeriodDays} days
            </span>
          </div>

          {/* Break-even Date */}
          <div className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
            <p className="text-sm text-blue-900 dark:text-blue-100 text-center">
              You'll break even by <strong>{results.breakEvenDate}</strong>
            </p>
          </div>

          {/* Annual ROI */}
          <div className="p-4 bg-gradient-to-r from-blue-600 to-blue-700 rounded-lg text-white">
            <div className="text-center">
              <p className="text-sm opacity-90 mb-1">Annual ROI</p>
              <p className="text-4xl font-bold">
                {results.annualROI > 0 ? '+' : ''}{Math.round(results.annualROI)}%
              </p>
              <p className="text-xs opacity-75 mt-2">
                {formatCurrency(results.monthlySavings * 12)}/year savings vs {formatCurrency(monthlyPrice * 12)}/year cost
              </p>
            </div>
          </div>

          {/* Upgrade CTA */}
          {onUpgrade && (
            <Button
              onClick={onUpgrade}
              variant="primary"
              className="w-full py-4 text-base font-semibold flex items-center justify-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all"
            >
              <span>Upgrade to {targetTier.charAt(0).toUpperCase() + targetTier.slice(1)}</span>
              <ArrowRight className="w-5 h-5" />
            </Button>
          )}

          {/* Disclaimer */}
          <p className="text-xs text-[var(--text-secondary)] text-center mt-4">
            *Estimates based on average bakery performance. Actual results may vary based on your specific operations, usage patterns, and implementation.
          </p>
        </div>
      )}
        </>
      )}
    </Card>
  );
};
