'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { GiftCertificateManagement } from '@/components/accounting/GiftCertificateManagement';
import { GiftCertificateDetail } from '@/components/accounting/GiftCertificateManagement/GiftCertificateDetail';
import { getGiftCertificateById } from '@/components/accounting/GiftCertificateManagement/actions';
import type { GiftCertificateFormData } from '@/components/accounting/GiftCertificateManagement/types';
import { ListPageSkeleton } from '@/components/ui/skeleton';

export default function GiftCertificatesPage() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');
  const id = searchParams.get('id');

  const [editData, setEditData] = useState<GiftCertificateFormData | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if ((mode === 'edit' || mode === 'view') && id) {
      setIsLoading(true);
      getGiftCertificateById(id)
        .then((result) => {
          if (result.success && result.data) {
            setEditData(result.data);
          }
        })
        .finally(() => setIsLoading(false));
    }
  }, [mode, id]);

  if (mode === 'new') {
    return <GiftCertificateDetail mode="new" />;
  }

  if (mode === 'view' && id) {
    if (isLoading) return <ListPageSkeleton showStats statsCount={4} tableColumns={8} />;
    return (
      <GiftCertificateDetail
        mode="view"
        id={id}
        initialData={editData ?? undefined}
      />
    );
  }

  if (mode === 'edit' && id) {
    if (isLoading) return <ListPageSkeleton showStats statsCount={4} tableColumns={8} />;
    return (
      <GiftCertificateDetail
        mode="edit"
        id={id}
        initialData={editData ?? undefined}
      />
    );
  }

  // 목록 - 컴포넌트가 자체 데이터 로딩 처리
  return <GiftCertificateManagement />;
}
