'use client';

/**
 * 차량 관리 상세/등록/수정 컴포넌트
 * IntegratedDetailTemplate 기반
 */

import { useRouter } from 'next/navigation';
import { useTransition } from 'react';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { Vehicle, VehicleFormData } from '../types';
import { vehicleDetailConfig, vehicleCreateConfig, vehicleEditConfig } from './config';
import {
  createVehicle,
  updateVehicle,
  deleteVehicle,
} from '../VehicleList/actions';

// ===== Props 타입 =====
interface VehicleDetailProps {
  mode: 'create' | 'view' | 'edit';
  initialData?: Vehicle;
  id?: string;
}

export function VehicleDetail({ mode, initialData, id }: VehicleDetailProps) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  // ===== 설정 선택 =====
  const getConfig = () => {
    switch (mode) {
      case 'create':
        return vehicleCreateConfig;
      case 'edit':
        return vehicleEditConfig;
      default:
        return vehicleDetailConfig;
    }
  };

  // ===== 저장 핸들러 =====
  const handleSave = async (formData: Record<string, unknown>) => {
    const vehicleData = vehicleDetailConfig.transformSubmitData?.(formData) as Partial<VehicleFormData>;

    startTransition(async () => {
      try {
        if (mode === 'create') {
          const result = await createVehicle(vehicleData);
          if (result.success) {
            toast.success('차량이 등록되었습니다.');
            router.push('/vehicle-management/vehicle');
          } else {
            toast.error(result.error || '등록에 실패했습니다.');
          }
        } else if (mode === 'edit' && id) {
          const result = await updateVehicle(id, vehicleData);
          if (result.success) {
            toast.success('차량 정보가 수정되었습니다.');
            router.push(`/vehicle-management/vehicle/${id}?mode=view`);
          } else {
            toast.error(result.error || '수정에 실패했습니다.');
          }
        }
      } catch (error) {
        console.error('Save error:', error);
        toast.error('저장 중 오류가 발생했습니다.');
      }
    });
  };

  // ===== 삭제 핸들러 =====
  const handleDelete = async () => {
    if (!id) return;

    startTransition(async () => {
      try {
        const result = await deleteVehicle(id);
        if (result.success) {
          toast.success('차량이 삭제되었습니다.');
          router.push('/vehicle-management/vehicle');
        } else {
          toast.error(result.error || '삭제에 실패했습니다.');
        }
      } catch (error) {
        console.error('Delete error:', error);
        toast.error('삭제 중 오류가 발생했습니다.');
      }
    });
  };

  // ===== 수정 모드 전환 =====
  const handleEdit = () => {
    if (id) {
      router.push(`/vehicle-management/vehicle/${id}?mode=edit`);
    }
  };

  // ===== 목록으로 이동 =====
  const handleBack = () => {
    router.push('/vehicle-management/vehicle');
  };

  // ===== 초기 데이터 변환 =====
  const transformedData = initialData && vehicleDetailConfig.transformInitialData
    ? vehicleDetailConfig.transformInitialData(initialData)
    : undefined;

  return (
    <IntegratedDetailTemplate
      config={getConfig()}
      mode={mode}
      initialData={transformedData}
      onSave={handleSave}
      onDelete={handleDelete}
      onEdit={handleEdit}
      onBack={handleBack}
      isLoading={isPending}
    />
  );
}

export default VehicleDetail;