'use client';

/**
 * 사원관리 페이지 (Employee Management)
 */

import { Suspense } from 'react';
import { useSearchParams, useRouter, useParams } from 'next/navigation';
import { EmployeeManagement } from '@/components/hr/EmployeeManagement';
import { EmployeeForm } from '@/components/hr/EmployeeManagement/EmployeeForm';
import { createEmployee } from '@/components/hr/EmployeeManagement/actions';
import { ListPageSkeleton } from '@/components/ui/skeleton';
import { toast } from 'sonner';
import type { EmployeeFormData } from '@/components/hr/EmployeeManagement/types';

function formatErrorMessage(result: {
  error?: string;
  errors?: Record<string, string[]>;
  status?: number;
}): string {
  const parts: string[] = [];
  if (result.status) parts.push(`[${result.status}]`);
  if (result.error) parts.push(result.error);
  if (result.errors) {
    const errorMessages = Object.entries(result.errors)
      .map(([field, messages]) => `${field}: ${messages[0]}`)
      .join(', ');
    if (errorMessages) parts.push(`(${errorMessages})`);
  }
  return parts.join(' ') || '알 수 없는 오류가 발생했습니다.';
}

function EmployeeManagementContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const params = useParams();
  const mode = searchParams.get('mode');
  const locale = params.locale as string || 'ko';

  if (mode === 'new') {
    const handleSave = async (data: EmployeeFormData): Promise<{ success: boolean; error?: string }> => {
      try {
        const result = await createEmployee(data);
        if (result.success) {
          toast.success('사원이 등록되었습니다.');
          router.push(`/${locale}/hr/employee-management`);
          return { success: true };
        } else {
          const errorMessage = formatErrorMessage(result);
          toast.error(errorMessage);
          return { success: false, error: errorMessage };
        }
      } catch (_error) {
        toast.error('서버 오류가 발생했습니다.');
        return { success: false, error: '서버 오류가 발생했습니다.' };
      }
    };

    return <EmployeeForm mode="create" onSave={handleSave} />;
  }

  return <EmployeeManagement />;
}

export default function EmployeeManagementPage() {
  return (
    <Suspense fallback={<ListPageSkeleton showHeader={false} showStats={true} statsCount={4} />}>
      <EmployeeManagementContent />
    </Suspense>
  );
}
