'use client';

import { useRouter, useParams, useSearchParams } from 'next/navigation';
import { useState, useEffect, useCallback } from 'react';
import { EmployeeForm } from '@/components/hr/EmployeeManagement/EmployeeForm';
import { getEmployeeById, deleteEmployee, updateEmployee } from '@/components/hr/EmployeeManagement/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { DetailPageSkeleton } from '@/components/ui/skeleton';
import type { Employee, EmployeeFormData } from '@/components/hr/EmployeeManagement/types';

export default function EmployeeDetailPage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode') === 'edit' ? 'edit' : 'view';
  const [employee, setEmployee] = useState<Employee | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // 직원 데이터 조회
  const fetchEmployee = useCallback(async () => {
    const id = params.id as string;
    if (!id) return;

    setIsLoading(true);
    try {
      const data = await getEmployeeById(id);
      // __authError 처리
      if (data && '__authError' in data) {
        router.push('/ko/login');
        return;
      }
      setEmployee(data);
    } catch (error) {
      console.error('[EmployeeDetailPage] fetchEmployee error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [params.id, router]);

  useEffect(() => {
    fetchEmployee();
  }, [fetchEmployee]);

  const handleEdit = () => {
    router.push(`/ko/hr/employee-management/${params.id}?mode=edit`);
  };

  const handleSave = async (data: EmployeeFormData): Promise<{ success: boolean; error?: string }> => {
    const id = params.id as string;
    if (!id) return { success: false, error: 'ID가 없습니다.' };

    try {
      const result = await updateEmployee(id, data);
      if (result.success) {
        // 데이터 갱신
        await fetchEmployee();
        return { success: true };
      } else {
        console.error('[EmployeeDetailPage] Update failed:', result.error);
        return { success: false, error: result.error };
      }
    } catch (error) {
      console.error('[EmployeeDetailPage] Update error:', error);
      return { success: false, error: '저장 중 오류가 발생했습니다.' };
    }
  };

  const handleDelete = () => {
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    const id = params.id as string;
    if (!id) return;

    setIsDeleting(true);
    try {
      const result = await deleteEmployee(id);
      if (result.success) {
        router.push('/ko/hr/employee-management');
      } else {
        console.error('[EmployeeDetailPage] Delete failed:', result.error);
      }
    } catch (error) {
      console.error('[EmployeeDetailPage] Delete error:', error);
    } finally {
      setIsDeleting(false);
      setDeleteDialogOpen(false);
    }
  };

  if (isLoading) {
    return <DetailPageSkeleton sections={2} fieldsPerSection={8} />;
  }

  if (!employee) {
    return (
      <ServerErrorPage
        title="사원 정보를 불러올 수 없습니다"
        message="사원 정보를 찾을 수 없습니다."
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <>
      <EmployeeForm
        mode={mode}
        employee={employee}
        {...(mode === 'edit'
          ? { onSave: handleSave }
          : { onEdit: handleEdit, onDelete: handleDelete }
        )}
      />

      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={confirmDelete}
        title="사원 삭제"
        description={
          <>
            &quot;{employee.name}&quot; 사원을 삭제하시겠습니까?
            <br />
            <span className="text-destructive">
              삭제된 사원 정보는 복구할 수 없습니다.
            </span>
          </>
        }
        loading={isDeleting}
      />
    </>
  );
}
