/**
 * LaborDetailClient - IntegratedDetailTemplate 기반 노임 상세/등록/수정
 *
 * 기존 LaborDetailClient를 IntegratedDetailTemplate으로 마이그레이션
 * - 6개 필드: 노임번호, 구분, 최소M, 최대M, 노임단가, 상태
 */

'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import {
  IntegratedDetailTemplate,
  type DetailMode,
} from '@/components/templates/IntegratedDetailTemplate';
import { laborDetailConfig } from './laborDetailConfig';
import type { Labor, LaborFormData } from './types';
import { getLabor, createLabor, updateLabor, deleteLabor } from './actions';

interface LaborDetailClientProps {
  laborId?: string;
  initialMode?: DetailMode;
}

export default function LaborDetailClient({
  laborId,
  initialMode = 'view',
}: LaborDetailClientProps) {
  const router = useRouter();
  const [labor, setLabor] = useState<Labor | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(false);
  const [mode, setMode] = useState<DetailMode>(initialMode);

  // 데이터 로드
  useEffect(() => {
    if (laborId && initialMode !== 'create') {
      const loadData = async () => {
        setIsLoading(true);
        try {
          const result = await getLabor(laborId);
          if (result.success && result.data) {
            setLabor(result.data);
          } else {
            toast.error(result.error || '노임 정보를 불러오는데 실패했습니다.');
            router.push('/ko/construction/order/base-info/labor');
          }
        } catch {
          toast.error('노임 정보를 불러오는데 실패했습니다.');
          router.push('/ko/construction/order/base-info/labor');
        } finally {
          setIsLoading(false);
        }
      };
      loadData();
    }
  }, [laborId, initialMode, router]);

  // 저장 핸들러
  const handleSubmit = useCallback(
    async (formData: Record<string, unknown>) => {
      try {
        const submitData = laborDetailConfig.transformSubmitData!(formData) as unknown as LaborFormData;

        if (mode === 'create') {
          const result = await createLabor(submitData);
          if (result.success && result.data) {
            return { success: true };
          }
          return { success: false, error: result.error || '노임 등록에 실패했습니다.' };
        } else if (mode === 'edit' && laborId) {
          const result = await updateLabor(laborId, submitData);
          if (result.success) {
            return { success: true };
          }
          return { success: false, error: result.error || '노임 수정에 실패했습니다.' };
        }

        return { success: false, error: '알 수 없는 오류가 발생했습니다.' };
      } catch {
        return { success: false, error: '저장 중 오류가 발생했습니다.' };
      }
    },
    [mode, laborId]
  );

  // 삭제 핸들러
  const handleDelete = useCallback(async (id: string | number) => {
    try {
      const result = await deleteLabor(String(id));
      if (result.success) {
        return { success: true };
      }
      return { success: false, error: result.error || '노임 삭제에 실패했습니다.' };
    } catch {
      return { success: false, error: '삭제 중 오류가 발생했습니다.' };
    }
  }, []);

  // 모드 변경 핸들러
  const handleModeChange = useCallback((newMode: DetailMode) => {
    setMode(newMode);
  }, []);

  return (
    <IntegratedDetailTemplate
      config={laborDetailConfig as Parameters<typeof IntegratedDetailTemplate>[0]['config']}
      mode={mode}
      initialData={labor as Record<string, unknown> | undefined}
      itemId={laborId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
      onModeChange={handleModeChange}
    />
  );
}

// Named export for backwards compatibility
export { LaborDetailClient };
