/**
 * 거래처 상세 페이지
 */

"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { ClientDetail } from "@/components/clients/ClientDetail";
import { useClientList, Client } from "@/hooks/useClientList";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { ContentLoadingSpinner } from "@/components/ui/loading-spinner";

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

  const { fetchClient, deleteClient } = useClientList();
  const [client, setClient] = useState<Client | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

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

      setIsLoading(true);
      try {
        const data = await fetchClient(id);
        if (data) {
          setClient(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");
  };

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

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await deleteClient(id);
      toast.success("거래처가 삭제되었습니다.");
      router.push("/sales/client-management-sales-admin");
    } catch (error) {
      toast.error("삭제 중 오류가 발생했습니다.");
    } finally {
      setIsDeleting(false);
      setShowDeleteDialog(false);
    }
  };

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

  if (!client) {
    return null;
  }

  return (
    <>
      <ClientDetail
        client={client}
        onBack={handleBack}
        onEdit={handleEdit}
        onDelete={() => setShowDeleteDialog(true)}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>거래처 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              &apos;{client.name}&apos; 거래처를 삭제하시겠습니까?
              <br />
              이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeleting ? "삭제 중..." : "삭제"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}