'use client';

/**
 * 차량일지/월간사진기록 상세/등록/수정 컴포넌트
 */

import { useRouter } from 'next/navigation';
import { useTransition } from 'react';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { VehicleLog, VehicleLogFormData } from '../types';
import { vehicleLogDetailConfig, vehicleLogCreateConfig, vehicleLogEditConfig } from './config';
import {
  createVehicleLog,
  updateVehicleLog,
  deleteVehicleLog,
} from '../VehicleLogList/actions';

interface VehicleLogDetailProps {
  mode: 'create' | 'view' | 'edit';
  initialData?: VehicleLog;
  id?: string;
}

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

  const getConfig = () => {
    switch (mode) {
      case 'create':
        return vehicleLogCreateConfig;
      case 'edit':
        return vehicleLogEditConfig;
      default:
        return vehicleLogDetailConfig;
    }
  };

  const handleSave = async (formData: Record<string, unknown>) => {
    const logData = vehicleLogDetailConfig.transformSubmitData?.(formData) as Partial<VehicleLogFormData>;

    startTransition(async () => {
      try {
        if (mode === 'create') {
          const result = await createVehicleLog(logData);
          if (result.success) {
            toast.success('차량일지가 등록되었습니다.');
            router.push('/vehicle-management/vehicle-log');
          } else {
            toast.error(result.error || '등록에 실패했습니다.');
          }
        } else if (mode === 'edit' && id) {
          const result = await updateVehicleLog(id, logData);
          if (result.success) {
            toast.success('차량일지가 수정되었습니다.');
            router.push(`/vehicle-management/vehicle-log/${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 deleteVehicleLog(id);
        if (result.success) {
          toast.success('차량일지가 삭제되었습니다.');
          router.push('/vehicle-management/vehicle-log');
        } else {
          toast.error(result.error || '삭제에 실패했습니다.');
        }
      } catch (error) {
        console.error('Delete error:', error);
        toast.error('삭제 중 오류가 발생했습니다.');
      }
    });
  };

  const handleEdit = () => {
    if (id) {
      router.push(`/vehicle-management/vehicle-log/${id}?mode=edit`);
    }
  };

  const handleBack = () => {
    router.push('/vehicle-management/vehicle-log');
  };

  const transformedData = initialData && vehicleLogDetailConfig.transformInitialData
    ? vehicleLogDetailConfig.transformInitialData(initialData)
    : undefined;

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

export default VehicleLogDetail;
