'use client';

import { useState, useEffect } from 'react';
import { VehicleForm } from './VehicleForm';
import { getVehicle, type VehicleResponse } from '@/lib/vehicles';

interface VehicleEditFormProps {
  vehicleId: string;
}

export function VehicleEditForm({ vehicleId }: VehicleEditFormProps) {
  const [vehicle, setVehicle] = useState<VehicleResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchVehicle() {
      setLoading(true);
      setError(null);
      try {
        const data = await getVehicle(vehicleId);
        setVehicle(data);
      } catch (err: unknown) {
        const apiErr = err as { error?: { message?: string } };
        setError(apiErr?.error?.message || 'Failed to load vehicle');
      } finally {
        setLoading(false);
      }
    }
    fetchVehicle();
  }, [vehicleId]);

  if (loading) {
    return (
      <div data-testid="vehicle-edit-loading" className="text-center py-8 text-text-muted">
        Loading vehicle...
      </div>
    );
  }

  if (error) {
    return (
      <div data-testid="vehicle-edit-error" className="p-4 bg-error/10 text-error rounded-lg">
        {error}
      </div>
    );
  }

  if (!vehicle) {
    return (
      <div data-testid="vehicle-edit-not-found" className="text-center py-8 text-text-muted">
        Vehicle not found
      </div>
    );
  }

  return <VehicleForm vehicle={vehicle} mode="edit" />;
}
