'use client';

/**
 * 차량 상세/수정 페이지
 */

import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { VehicleDetail } from '@/components/vehicle-management/VehicleDetail';
import { getVehicleById } from '@/components/vehicle-management/VehicleList/actions';
import type { Vehicle } from '@/components/vehicle-management/types';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

export default function VehicleDetailPage() {
  const params = useParams();
  const id = params.id as string;
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode') === 'edit' ? 'edit' : 'view';

  const [data, setData] = useState<Vehicle | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) return;

    getVehicleById(id)
      .then((result) => {
        if (result.success && result.data) {
          setData(result.data);
        } else {
          setError(result.error || '데이터를 불러올 수 없습니다.');
        }
      })
      .finally(() => setIsLoading(false));
  }, [id]);

  if (isLoading) return <GenericPageSkeleton />;

  if (error || !data) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-red-500">{error || '차량을 찾을 수 없습니다.'}</div>
      </div>
    );
  }

  return <VehicleDetail mode={mode} initialData={data} id={id} />;
}
