import React, { useState, useCallback } from 'react';
import { Route } from 'lucide-react';
import type { VesselData, TripEstimate, CurrencyCode } from '../types';
import { calculateTripCarbon, calculateCarbonFromFuel } from '../utils/carbonCalculator';
import { currencies, formatCurrency } from '../utils/currencies';
import { CurrencySelect } from './CurrencySelect';

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

export function TripCalculator({ vesselData, onOffsetClick }: Props) {
  const [calculationType, setCalculationType] = useState<'fuel' | 'distance' | 'custom'>('fuel');
  const [distance, setDistance] = useState<string>('');
  const [speed, setSpeed] = useState<string>('12');
  const [fuelRate, setFuelRate] = useState<string>('100');
  const [fuelAmount, setFuelAmount] = useState<string>('');
  const [fuelUnit, setFuelUnit] = useState<'liters' | 'gallons'>('liters');
  const [tripEstimate, setTripEstimate] = useState<TripEstimate | null>(null);
  const [currency, setCurrency] = useState<CurrencyCode>('USD');
  const [offsetPercentage, setOffsetPercentage] = useState<number>(100);
  const [customPercentage, setCustomPercentage] = useState<string>('');
  const [customAmount, setCustomAmount] = useState<string>('');

  const handleCalculate = useCallback((e: React.FormEvent) => {
    e.preventDefault();
    if (calculationType === 'distance') {
      const estimate = calculateTripCarbon(
        vesselData,
        Number(distance),
        Number(speed),
        Number(fuelRate)
      );
      setTripEstimate(estimate);
    } else if (calculationType === 'fuel') {
      const co2Emissions = calculateCarbonFromFuel(Number(fuelAmount), fuelUnit === 'gallons');
      setTripEstimate({
        distance: 0,
        duration: 0,
        fuelConsumption: Number(fuelAmount),
        co2Emissions
      });
    }
  }, [calculationType, distance, speed, fuelRate, fuelAmount, fuelUnit, vesselData]);

  const handleCustomPercentageChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === '' || (Number(value) >= 0 && Number(value) <= 100)) {
      setCustomPercentage(value);
      if (value !== '') {
        setOffsetPercentage(Number(value));
      }
    }
  }, []);

  const handlePresetPercentage = useCallback((percentage: number) => {
    setOffsetPercentage(percentage);
    setCustomPercentage('');
  }, []);

  const calculateOffsetAmount = useCallback((emissions: number, percentage: number) => {
    return (emissions * percentage) / 100;
  }, []);

  const handleCustomAmountChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === '' || Number(value) >= 0) {
      setCustomAmount(value);
    }
  }, []);

  return (
    <div className="bg-white rounded-lg shadow-xl p-6 max-w-2xl w-full mt-8">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold text-gray-800">Carbon Offset Calculator</h2>
        <Route className="text-blue-500" size={24} />
      </div>

      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Calculation Method
        </label>
        <div className="flex flex-wrap gap-3">
          <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'
            }`}
          >
            Fuel Based
          </button>
          <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'
            }`}
          >
            Distance Based
          </button>
          <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'
            }`}
          >
            Custom Amount
          </button>
        </div>
      </div>

      {calculationType === 'custom' ? (
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Select Currency
            </label>
            <div className="max-w-xs">
              <CurrencySelect value={currency} onChange={setCurrency} />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Enter Amount to Offset
            </label>
            <div className="relative rounded-md shadow-sm">
              <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                <span className="text-gray-500 sm:text-sm">{currencies[currency].symbol}</span>
              </div>
              <input
                type="number"
                value={customAmount}
                onChange={handleCustomAmountChange}
                placeholder="Enter amount"
                min="0"
                className="mt-1 block w-full rounded-md border-gray-300 pl-7 pr-12 focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                required
              />
              <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
                <span className="text-gray-500 sm:text-sm">{currency}</span>
              </div>
            </div>
          </div>

          {customAmount && Number(customAmount) > 0 && (
            <button 
              onClick={() => onOffsetClick?.(0, Number(customAmount))}
              className="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors mt-6"
            >
              Offset Your Impact
            </button>
          )}
        </div>
      ) : (
        <form onSubmit={handleCalculate} className="space-y-4">
          {calculationType === 'fuel' && (
            <div>
              <label className="block text-sm font-medium text-gray-700">
                Fuel Consumption
              </label>
              <div className="flex space-x-4">
                <div className="flex-1">
                  <input
                    type="number"
                    min="1"
                    value={fuelAmount}
                    onChange={(e) => setFuelAmount(e.target.value)}
                    placeholder="Enter amount"
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200"
                    required
                  />
                </div>
                <div>
                  <select
                    value={fuelUnit}
                    onChange={(e) => setFuelUnit(e.target.value as 'liters' | 'gallons')}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200"
                  >
                    <option value="liters">Liters</option>
                    <option value="gallons">Gallons</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {calculationType === 'distance' && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Distance (nautical miles)
                </label>
                <input
                  type="number"
                  min="1"
                  value={distance}
                  onChange={(e) => setDistance(e.target.value)}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Average Speed (knots)
                </label>
                <input
                  type="number"
                  min="1"
                  max="50"
                  value={speed}
                  onChange={(e) => setSpeed(e.target.value)}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Fuel Consumption Rate (liters per hour)
                </label>
                <input
                  type="number"
                  min="1"
                  step="1"
                  value={fuelRate}
                  onChange={(e) => setFuelRate(e.target.value)}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200"
                  required
                />
                <p className="mt-1 text-sm text-gray-500">
                  Typical range: 50 - 500 liters per hour for most yachts
                </p>
              </div>
            </>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700">
              Select Currency
            </label>
            <div className="max-w-xs">
              <CurrencySelect value={currency} onChange={setCurrency} />
            </div>
          </div>

          <button
            type="submit"
            className="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors"
          >
            Calculate Impact
          </button>
        </form>
      )}

      {tripEstimate && calculationType !== 'custom' && (
        <div className="mt-6 space-y-6">
          <div className="grid grid-cols-2 gap-4">
            {calculationType === 'distance' && (
              <div className="bg-gray-50 p-4 rounded-lg">
                <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>
              </div>
            )}
            <div className="bg-gray-50 p-4 rounded-lg">
              <p className="text-sm text-gray-600">Fuel Consumption</p>
              <p className="text-xl font-bold text-gray-900">
                {tripEstimate.fuelConsumption.toLocaleString()} {fuelUnit}
              </p>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Offset Percentage
            </label>
            <div className="flex flex-wrap gap-3 mb-3">
              {[100, 75, 50, 25].map((percent) => (
                <button
                  key={percent}
                  type="button"
                  onClick={() => handlePresetPercentage(percent)}
                  className={`px-4 py-2 rounded-lg transition-colors ${
                    offsetPercentage === percent && customPercentage === ''
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  {percent}%
                </button>
              ))}
              <div className="flex items-center space-x-2">
                <input
                  type="number"
                  value={customPercentage}
                  onChange={handleCustomPercentageChange}
                  placeholder="Custom %"
                  min="0"
                  max="100"
                  className="w-24 px-3 py-2 border rounded-lg focus:ring-blue-500 focus:border-blue-500"
                />
                <span className="text-gray-600">%</span>
              </div>
            </div>
          </div>
          
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-sm text-gray-600">Selected CO₂ Offset</p>
            <p className="text-2xl font-bold text-blue-900">
              {calculateOffsetAmount(tripEstimate.co2Emissions, offsetPercentage).toFixed(2)} tons
            </p>
            <p className="text-sm text-blue-600 mt-1">
              {offsetPercentage}% of {tripEstimate.co2Emissions.toFixed(2)} tons
            </p>
          </div>

          <button 
            onClick={() => onOffsetClick?.(calculateOffsetAmount(tripEstimate.co2Emissions, offsetPercentage))}
            className="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors"
          >
            Offset Your Impact
          </button>
        </div>
      )}
    </div>
  );
}