import { useState, useEffect } from 'react';
import { useVehicles } from '../../vehicles/hooks/useVehicles';
import { VehicleSelectionDialog } from './VehicleSelectionDialog';
import type { SubscriptionTier } from '../types/subscription.types';

interface DowngradeFlowProps {
  targetTier: SubscriptionTier;
  onComplete: (vehicleIdsToKeep: string[]) => void;
  onCancel: () => void;
}

const TIER_LIMITS: Record<SubscriptionTier, number | null> = {
  free: 2,
  pro: 5,
  enterprise: null, // unlimited
};

export const DowngradeFlow = ({
  targetTier,
  onComplete,
  onCancel,
}: DowngradeFlowProps) => {
  const { data: vehicles } = useVehicles();
  const [showVehicleSelection, setShowVehicleSelection] = useState(false);

  useEffect(() => {
    // Check if vehicle selection is needed
    const targetLimit = TIER_LIMITS[targetTier];
    const vehicleCount = vehicles?.length || 0;

    if (targetLimit !== null && vehicleCount > targetLimit) {
      // Vehicle count exceeds target tier limit - show selection dialog
      setShowVehicleSelection(true);
    } else {
      // No selection needed - directly downgrade with all vehicles
      const allVehicleIds = vehicles?.map((v: any) => v.id) || [];
      onComplete(allVehicleIds);
    }
  }, [vehicles, targetTier, onComplete]);

  const handleVehicleSelectionConfirm = (selectedVehicleIds: string[]) => {
    setShowVehicleSelection(false);
    onComplete(selectedVehicleIds);
  };

  const handleVehicleSelectionCancel = () => {
    setShowVehicleSelection(false);
    onCancel();
  };

  if (!showVehicleSelection) {
    return null;
  }

  const targetLimit = TIER_LIMITS[targetTier];

  return (
    <VehicleSelectionDialog
      open={showVehicleSelection}
      onClose={handleVehicleSelectionCancel}
      onConfirm={handleVehicleSelectionConfirm}
      vehicles={vehicles || []}
      maxSelections={targetLimit || 0}
      targetTier={targetTier}
    />
  );
};
