'use client';

/**
 * 지게차 관리 상세/등록/수정 컴포넌트
 */

import { useRouter } from 'next/navigation';
import { useTransition } from 'react';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { Forklift, ForkliftFormData } from '../types';
import { forkliftDetailConfig, forkliftCreateConfig, forkliftEditConfig } from './config';
import {
  createForklift,
  updateForklift,
  deleteForklift,
} from '../ForkliftList/actions';

interface ForkliftDetailProps {
  mode: 'create' | 'view' | 'edit';
  initialData?: Forklift;
  id?: string;
}

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

  const getConfig = () => {
    switch (mode) {
      case 'create':
        return forkliftCreateConfig;
      case 'edit':
        return forkliftEditConfig;
      default:
        return forkliftDetailConfig;
    }
  };

  const handleSave = async (formData: Record<string, unknown>) => {
    const forkliftData = forkliftDetailConfig.transformSubmitData?.(formData) as Partial<ForkliftFormData>;

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

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

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

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

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

export default ForkliftDetail;
