import { useState, useCallback, useEffect } from 'react';
import { Calculator, ArrowLeft, Zap, Route, DollarSign } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import type { VesselData, TripEstimate, CurrencyCode } from '../types';
import { calculateTripCarbon, calculateCarbonFromFuel } from '../utils/carbonCalculator';
import { currencies, formatCurrency, getCurrencyByCode } from '../utils/currencies';
import { CurrencySelect } from './CurrencySelect';
import { PWAInstallPrompt } from './PWAInstallPrompt';
import { MobileOffsetOrder } from './MobileOffsetOrder';
import { useCalculatorState } from '../hooks/useCalculatorState';

interface Props {
  vesselData: VesselData;
  onBack?: () => void;
}

export function MobileCalculator({ vesselData, onBack }: Props) {
  const { state: savedState, saveState } = useCalculatorState();

  const [calculationType, setCalculationType] = useState<'fuel' | 'distance' | 'custom'>(
    savedState?.calculationType || 'fuel'
  );
  const [distance, setDistance] = useState<string>(savedState?.distance || '');
  const [speed, setSpeed] = useState<string>(savedState?.speed || '12');
  const [fuelRate, setFuelRate] = useState<string>(savedState?.fuelRate || '100');
  const [fuelAmount, setFuelAmount] = useState<string>(savedState?.fuelAmount || '');

  // Format number with commas
  const formatNumber = (value: string): string => {
    const num = value.replace(/,/g, '');
    if (num === '') return '';
    const parts = num.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
  };

  // Format tons for display
  const formatTons = (tons: number): string => {
    const fixed = tons.toFixed(2);
    const parts = fixed.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
  };

  const handleFuelAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/,/g, '');
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setFuelAmount(formatNumber(value));
    }
  };

  const handleDistanceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/,/g, '');
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setDistance(formatNumber(value));
    }
  };

  const handleSpeedChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/,/g, '');
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setSpeed(formatNumber(value));
    }
  };

  const handleFuelRateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/,/g, '');
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setFuelRate(formatNumber(value));
    }
  };
  const [fuelUnit, setFuelUnit] = useState<'liters' | 'gallons'>(
    savedState?.fuelUnit || 'liters'
  );
  const [tripEstimate, setTripEstimate] = useState<TripEstimate | null>(null);
  const [currency, setCurrency] = useState<CurrencyCode>('USD');
  const [customAmount, setCustomAmount] = useState<string>(savedState?.customAmount || '');
  const [showOffsetOrder, setShowOffsetOrder] = useState(false);
  const [offsetTons, setOffsetTons] = useState(0);
  const [monetaryAmount, setMonetaryAmount] = useState<number | undefined>();

  const handleCalculate = useCallback((e: React.FormEvent) => {
    e.preventDefault();

    // Save state before setting results
    saveState({
      calculationType,
      distance,
      speed,
      fuelRate,
      fuelAmount,
      fuelUnit,
      customAmount,
      offsetPercentage: 100,
    });

    if (calculationType === 'distance') {
      const estimate = calculateTripCarbon(
        Number(distance.replace(/,/g, '')),
        Number(speed.replace(/,/g, '')),
        Number(fuelRate.replace(/,/g, ''))
      );
      setTripEstimate(estimate);
    } else if (calculationType === 'fuel') {
      const co2Emissions = calculateCarbonFromFuel(Number(fuelAmount.replace(/,/g, '')), fuelUnit === 'gallons');
      setTripEstimate({
        distance: 0,
        duration: 0,
        fuelConsumption: Number(fuelAmount.replace(/,/g, '')),
        co2Emissions
      });
    }
  }, [calculationType, distance, speed, fuelRate, fuelAmount, fuelUnit, customAmount, vesselData, saveState]);


  const handleCustomAmountChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/,/g, '');
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setCustomAmount(formatNumber(value));
    }
  }, []);

  // Save state to localStorage whenever inputs change
  useEffect(() => {
    saveState({
      calculationType,
      distance,
      speed,
      fuelRate,
      fuelAmount,
      fuelUnit,
      customAmount,
      offsetPercentage: 100, // Default offset percentage
    });
  }, [calculationType, distance, speed, fuelRate, fuelAmount, fuelUnit, customAmount, saveState]);

  const calculationMethods = [
    { id: 'fuel', icon: Zap, label: 'Fuel Based', color: 'blue' },
    { id: 'distance', icon: Route, label: 'Distance', color: 'green' },
    { id: 'custom', icon: DollarSign, label: 'Custom Amount', color: 'purple' }
  ];

  if (showOffsetOrder) {
    return (
      <MobileOffsetOrder
        tons={offsetTons}
        monetaryAmount={monetaryAmount}
        onBack={() => setShowOffsetOrder(false)}
      />
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-cyan-50">
      {/* Mobile Header */}
      <motion.header 
        className="bg-white/80 backdrop-blur-md shadow-sm sticky top-0 z-50"
        initial={{ y: -100 }}
        animate={{ y: 0 }}
        transition={{ duration: 0.3 }}
      >
        <div className="flex items-center justify-between p-4">
          {onBack && (
            <motion.button
              onClick={onBack}
              className="p-2 rounded-xl bg-gray-100 hover:bg-gray-200 transition-colors"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <ArrowLeft size={20} />
            </motion.button>
          )}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center">
              <Calculator className="text-white" size={16} />
            </div>
            <h1 className="text-lg font-bold text-gray-900">Puffin Calculator</h1>
          </div>
          <div className="w-10"></div> {/* Spacer */}
        </div>
      </motion.header>

      <div className="p-4 pb-20">
        {/* Method Selection */}
        <motion.div 
          className="mb-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Select Calculation Method</h2>
          <div className="grid grid-cols-1 gap-3">
            {calculationMethods.map((method, index) => {
              const IconComponent = method.icon;
              const isActive = calculationType === method.id;
              
              return (
                <motion.button
                  key={method.id}
                  onClick={() => setCalculationType(method.id as any)}
                  className={`p-4 rounded-2xl border-2 transition-all ${
                    isActive
                      ? 'border-blue-500 bg-blue-50 shadow-lg'
                      : 'border-gray-200 bg-white hover:border-gray-300'
                  }`}
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.2 + index * 0.1 }}
                >
                  <div className="flex items-center space-x-3">
                    <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${
                      isActive 
                        ? 'bg-blue-500 text-white' 
                        : 'bg-gray-100 text-gray-600'
                    }`}>
                      <IconComponent size={20} />
                    </div>
                    <div className="text-left">
                      <div className={`font-semibold ${isActive ? 'text-blue-900' : 'text-gray-900'}`}>
                        {method.label}
                      </div>
                      <div className="text-sm text-gray-500">
                        {method.id === 'fuel' && 'Based on fuel consumption'}
                        {method.id === 'distance' && 'Based on trip distance'}
                        {method.id === 'custom' && 'Enter custom amount'}
                      </div>
                    </div>
                  </div>
                </motion.button>
              );
            })}
          </div>
        </motion.div>

        {/* Input Forms */}
        <AnimatePresence mode="wait">
          {calculationType === 'custom' ? (
            <motion.div 
              key="custom"
              className="space-y-6"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className="bg-white rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-semibold mb-4">Custom Amount</h3>
                
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Currency
                    </label>
                    <CurrencySelect value={currency} onChange={setCurrency} />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Amount to Offset
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                        <span className="text-gray-500 text-lg">{currencies[currency].symbol}</span>
                      </div>
                      <input
                        type="text"
                        value={customAmount}
                        onChange={handleCustomAmountChange}
                        placeholder="0.00"
                        className="w-full pl-10 pr-16 py-4 text-lg border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                      <div className="absolute inset-y-0 right-0 pr-4 flex items-center pointer-events-none">
                        <span className="text-gray-500 text-sm font-medium">{currency}</span>
                      </div>
                    </div>
                  </div>
                </div>

                {customAmount && Number(customAmount.replace(/,/g, '')) > 0 && (
                  <motion.button
                    onClick={() => {
                      setOffsetTons(0);
                      setMonetaryAmount(Number(customAmount.replace(/,/g, '')));
                      setShowOffsetOrder(true);
                    }}
                    className="w-full mt-6 bg-gradient-to-r from-blue-500 to-blue-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all"
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                  >
                    Offset {formatCurrency(Number(customAmount.replace(/,/g, '')), getCurrencyByCode(currency))}
                  </motion.button>
                )}
              </div>
            </motion.div>
          ) : (
            <motion.form 
              key="calculator"
              onSubmit={handleCalculate} 
              className="space-y-6"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className="bg-white rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-semibold mb-4">
                  {calculationType === 'fuel' ? 'Fuel Consumption' : 'Trip Details'}
                </h3>

                {calculationType === 'fuel' && (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Fuel Amount
                      </label>
                      <input
                        type="text"
                        value={fuelAmount}
                        onChange={handleFuelAmountChange}
                        placeholder="Enter fuel amount"
                        className="w-full py-4 px-4 text-lg border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Unit
                      </label>
                      <div className="grid grid-cols-2 gap-3">
                        {['liters', 'gallons'].map((unit) => (
                          <button
                            key={unit}
                            type="button"
                            onClick={() => setFuelUnit(unit as 'liters' | 'gallons')}
                            className={`py-3 px-4 rounded-xl font-medium transition-colors ${
                              fuelUnit === unit
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                            }`}
                          >
                            {unit.charAt(0).toUpperCase() + unit.slice(1)}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                )}

                {calculationType === 'distance' && (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Distance (nautical miles)
                      </label>
                      <input
                        type="text"
                        value={distance}
                        onChange={handleDistanceChange}
                        placeholder="Enter distance"
                        className="w-full py-4 px-4 text-lg border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        required
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Average Speed (knots)
                      </label>
                      <input
                        type="text"
                        value={speed}
                        onChange={handleSpeedChange}
                        placeholder="Average speed"
                        className="w-full py-4 px-4 text-lg border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        required
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Fuel Rate (liters/hour)
                      </label>
                      <input
                        type="text"
                        value={fuelRate}
                        onChange={handleFuelRateChange}
                        placeholder="Fuel consumption rate"
                        className="w-full py-4 px-4 text-lg border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        required
                      />
                      <p className="mt-2 text-sm text-gray-500">
                        Typical: 50-500 L/h for most yachts
                      </p>
                    </div>
                  </div>
                )}

                <div className="mt-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Currency
                  </label>
                  <CurrencySelect value={currency} onChange={setCurrency} />
                </div>

                <button
                  type="submit"
                  className="w-full mt-6 bg-gradient-to-r from-blue-500 to-blue-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all"
                >
                  Calculate Carbon Impact
                </button>
              </div>
            </motion.form>
          )}
        </AnimatePresence>

        {/* Results */}
        <AnimatePresence>
          {tripEstimate && calculationType !== 'custom' && (
            <motion.div 
              className="mt-6 space-y-4"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
            >
              {/* Results Summary */}
              <div className="bg-white rounded-2xl p-6 shadow-sm">
                <h3 className="text-lg font-semibold mb-4">Trip Impact</h3>
                
                <div className="grid grid-cols-2 gap-4 mb-4">
                  {calculationType === 'distance' && (
                    <div className="bg-blue-50 p-4 rounded-xl text-center">
                      <div className="text-2xl font-bold text-blue-900">
                        {tripEstimate.duration.toFixed(1)}h
                      </div>
                      <div className="text-sm text-blue-600">Duration</div>
                    </div>
                  )}
                  <div className="bg-green-50 p-4 rounded-xl text-center">
                    <div className="text-2xl font-bold text-green-900">
                      {tripEstimate.fuelConsumption.toLocaleString()}
                    </div>
                    <div className="text-sm text-green-600">
                      {fuelUnit} consumed
                    </div>
                  </div>
                </div>

                <div className="bg-red-50 p-4 rounded-xl text-center">
                  <div className="text-3xl font-bold text-red-900">
                    {formatTons(tripEstimate.co2Emissions)} tons
                  </div>
                  <div className="text-sm text-red-600">CO₂ Emissions</div>
                </div>
              </div>

              {/* Action Button */}
              <div className="bg-white rounded-2xl p-6 shadow-sm">
                <button
                  onClick={() => {
                    setOffsetTons(tripEstimate.co2Emissions);
                    setMonetaryAmount(undefined);
                    setShowOffsetOrder(true);
                  }}
                  className="w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all"
                >
                  Calculate your Impact
                </button>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* PWA Install Prompt */}
      <PWAInstallPrompt />
    </div>
  );
}
