/**
 * 거래처 수정 페이지
 */

"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { ClientRegistration } from "@/components/clients/ClientRegistration";
import {
  useClientList,
  ClientFormData,
  clientToFormData,
} from "@/hooks/useClientList";
import { toast } from "sonner";
import { ContentLoadingSpinner } from "@/components/ui/loading-spinner";

export default function ClientEditPage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;

  const { fetchClient, updateClient, isLoading: hookLoading } = useClientList();
  const [editingClient, setEditingClient] = useState<ClientFormData | null>(
    null
  );
  const [isLoading, setIsLoading] = useState(true);

  // 데이터 로드
  useEffect(() => {
    const loadClient = async () => {
      if (!id) return;

      setIsLoading(true);
      try {
        const data = await fetchClient(id);
        if (data) {
          setEditingClient(clientToFormData(data));
        } else {
          toast.error("거래처를 찾을 수 없습니다.");
          router.push("/sales/client-management-sales-admin");
        }
      } catch (error) {
        toast.error("데이터 로드 중 오류가 발생했습니다.");
        router.push("/sales/client-management-sales-admin");
      } finally {
        setIsLoading(false);
      }
    };

    loadClient();
  }, [id, fetchClient, router]);

  const handleBack = () => {
    router.push(`/sales/client-management-sales-admin/${id}`);
  };

  const handleSave = async (formData: ClientFormData) => {
    await updateClient(id, formData);
  };

  if (isLoading) {
    return <ContentLoadingSpinner text="거래처 정보를 불러오는 중..." />;
  }

  if (!editingClient) {
    return null;
  }

  return (
    <ClientRegistration
      onBack={handleBack}
      onSave={handleSave}
      editingClient={editingClient}
      isLoading={hookLoading}
    />
  );
}