import { useState, useCallback, useEffect } from 'react';
import { Leaf, Droplet } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import type { VesselData, TripEstimate } from '../types';
import { calculateTripCarbon, calculateCarbonFromFuel } from '../utils/carbonCalculator';
import { FormSelect } from './forms/FormSelect';
import { useCalculatorState } from '../hooks/useCalculatorState';

interface Props {
  vesselData: VesselData;
  onOffsetClick?: (tons: number, monetaryAmount?: number) => void;
}

export function TripCalculator({ vesselData, onOffsetClick }: 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('.');
  };

  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 [customAmount, setCustomAmount] = useState<string>(savedState?.customAmount || '');

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

    // Save state before navigating
    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, ''))
      );
      // Immediately navigate to projects page without showing results
      onOffsetClick?.(estimate.co2Emissions);
    } else if (calculationType === 'fuel') {
      const co2Emissions = calculateCarbonFromFuel(Number(fuelAmount.replace(/,/g, '')), fuelUnit === 'gallons');
      // Immediately navigate to projects page without showing results
      onOffsetClick?.(co2Emissions);
    }
  }, [calculationType, distance, speed, fuelRate, fuelAmount, fuelUnit, customAmount, vesselData, onOffsetClick, 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 for TripCalculator
    });
  }, [calculationType, distance, speed, fuelRate, fuelAmount, fuelUnit, customAmount, saveState]);

  // Animation variants
  const fadeIn = {
    hidden: { opacity: 0 },
    visible: { 
      opacity: 1,
      transition: { duration: 0.5 }
    }
  };

  return (
    <motion.div 
      className="luxury-card p-8 max-w-4xl w-full mt-8"
      initial={{ opacity: 0, y: 30 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ 
        duration: 0.6,
        ease: [0.22, 1, 0.36, 1]
      }}
    >
      <div className="flex items-center justify-between mb-8">
        <motion.h2 
          className="text-3xl font-bold heading-luxury"
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          Carbon Calculator
        </motion.h2>
        <motion.div
          className="w-12 h-12 bg-gradient-to-br from-green-500 to-green-600 rounded-full flex items-center justify-center"
          initial={{ rotate: -10, opacity: 0, scale: 0.8 }}
          animate={{ rotate: 0, opacity: 1, scale: 1 }}
          transition={{ duration: 0.6, delay: 0.3, type: "spring", stiffness: 300 }}
        >
          <Leaf className="text-white" size={20} />
        </motion.div>
      </div>

      <motion.div 
        className="mb-6"
        variants={fadeIn}
        initial="hidden"
        animate="visible"
      >
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Calculation Method
        </label>
        <div className="flex flex-wrap gap-3">
          <motion.button
            type="button"
            onClick={() => setCalculationType('fuel')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              calculationType === 'fuel'
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            transition={{ type: "spring", stiffness: 400, damping: 17 }}
          >
            Fuel Based
          </motion.button>
          <motion.button
            type="button"
            onClick={() => setCalculationType('distance')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              calculationType === 'distance'
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            transition={{ type: "spring", stiffness: 400, damping: 17 }}
          >
            Distance Based
          </motion.button>
          <motion.button
            type="button"
            onClick={() => setCalculationType('custom')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              calculationType === 'custom'
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            transition={{ type: "spring", stiffness: 400, damping: 17 }}
          >
            Custom Amount
          </motion.button>
        </div>
      </motion.div>

      <AnimatePresence mode="wait">
        {calculationType === 'custom' ? (
          <motion.div
            key="custom"
            className="space-y-4 overflow-hidden"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.4, ease: "easeInOut" }}
          >
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Enter Amount to Offset
              </label>
              <div className="relative">
                <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
                  <span className="text-gray-500 text-sm font-semibold">$</span>
                </div>
                <input
                  type="text"
                  value={customAmount}
                  onChange={handleCustomAmountChange}
                  placeholder="Enter amount"
                  className="block w-full pl-10 pr-16 py-2.5 rounded-lg border border-gray-200 shadow-sm transition-all duration-200 text-sm text-gray-900 font-medium outline-none hover:border-gray-300 hover:shadow-md focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:shadow-md"
                  required
                />
                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-4">
                  <span className="text-gray-500 text-sm font-medium">USD</span>
                </div>
              </div>
            </div>

            {customAmount && Number(customAmount.replace(/,/g, '')) > 0 && (
              <motion.button
                onClick={() => onOffsetClick?.(0, Number(customAmount.replace(/,/g, '')))}
                className="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors mt-6"
                whileHover={{ scale: 1.03 }}
                whileTap={{ scale: 0.97 }}
              >
                Calculate your Impact
              </motion.button>
            )}
          </motion.div>
        ) : (
          <motion.form
            key="calculator"
            onSubmit={handleCalculate}
            className="space-y-4 overflow-hidden"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.4, ease: "easeInOut" }}
          >
            <AnimatePresence mode="wait">
              {calculationType === 'fuel' && (
                <motion.div
                  key="fuel"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.3, ease: "easeInOut" }}
                  className="grid grid-cols-2 gap-4 overflow-hidden"
                >
                  <div className="col-span-2">
                    <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="block w-full px-4 py-2.5 rounded-lg border border-gray-200 shadow-sm transition-all duration-200 text-sm text-gray-900 font-medium outline-none hover:border-gray-300 hover:shadow-md focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:shadow-md"
                      required
                    />
                  </div>
                  <div className="col-span-2">
                    <FormSelect
                      id="fuel-unit"
                      label="Unit"
                      icon={<Droplet size={20} />}
                      value={fuelUnit}
                      onChange={(e) => setFuelUnit(e.target.value as 'liters' | 'gallons')}
                    >
                      <option value="liters">Liters</option>
                      <option value="gallons">Gallons</option>
                    </FormSelect>
                  </div>
                </motion.div>
              )}

              {calculationType === 'distance' && (
                <motion.div
                  key="distance"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.3, ease: "easeInOut" }}
                  className="space-y-4 overflow-hidden"
                >
                  <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="block w-full px-4 py-2.5 rounded-lg border border-gray-200 shadow-sm transition-all duration-200 text-sm text-gray-900 font-medium outline-none hover:border-gray-300 hover:shadow-md focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:shadow-md"
                      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="Enter speed"
                      className="block w-full px-4 py-2.5 rounded-lg border border-gray-200 shadow-sm transition-all duration-200 text-sm text-gray-900 font-medium outline-none hover:border-gray-300 hover:shadow-md focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:shadow-md"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Fuel Consumption Rate (liters per hour)
                    </label>
                    <input
                      type="text"
                      value={fuelRate}
                      onChange={handleFuelRateChange}
                      placeholder="Enter fuel rate"
                      className="block w-full px-4 py-2.5 rounded-lg border border-gray-200 shadow-sm transition-all duration-200 text-sm text-gray-900 font-medium outline-none hover:border-gray-300 hover:shadow-md focus:border-blue-500 focus:ring-2 focus:ring-blue-100 focus:shadow-md"
                      required
                    />
                    <p className="mt-2 text-sm text-gray-500">
                      Typical range: 50 - 500 liters per hour for most yachts
                    </p>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            <motion.button
              type="submit"
              className="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors"
              whileHover={{ scale: 1.03 }}
              whileTap={{ scale: 0.97 }}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{
                duration: 0.3,
                delay: 0.4,
                type: "spring",
                stiffness: 400,
                damping: 17
              }}
            >
              Calculate Impact
            </motion.button>
          </motion.form>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {tripEstimate && calculationType !== 'custom' && (
          <motion.div 
            className="mt-6 space-y-6"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.5, ease: "easeOut" }}
          >
            <motion.div 
              className="grid grid-cols-2 gap-4"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              {calculationType === 'distance' && (
                <motion.div 
                  className="bg-gray-50 p-4 rounded-lg"
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.3 }}
                >
                  <p className="text-sm text-gray-600">Trip Duration</p>
                  <p className="text-xl font-bold text-gray-900">
                    {tripEstimate.duration.toFixed(1)} hours
                  </p>
                </motion.div>
              )}
              <motion.div 
                className="bg-gray-50 p-4 rounded-lg"
                initial={{ opacity: 0, x: calculationType === 'distance' ? 20 : 0 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.5, delay: 0.4 }}
              >
                <p className="text-sm text-gray-600">Fuel Consumption</p>
                <p className="text-xl font-bold text-gray-900">
                  {tripEstimate.fuelConsumption.toLocaleString()} {fuelUnit}
                </p>
              </motion.div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}
