'use client';

/**
 * 카드 상세/수정 페이지 - IntegratedDetailTemplate 적용
 */

import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { cardConfig } from '@/components/hr/CardManagement/cardConfig';
import {
  getCard,
  updateCard,
  deleteCard,
} from '@/components/hr/CardManagement/actions';
import type { Card, CardFormData } from '@/components/hr/CardManagement/types';
import type { DetailMode } from '@/components/templates/IntegratedDetailTemplate';

export default function CardDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const cardId = params.id as string;

  const [card, setCard] = useState<Card | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // URL에서 mode 파라미터 확인 (?mode=edit)
  const urlMode = searchParams.get('mode');
  const initialMode: DetailMode = urlMode === 'edit' ? 'edit' : 'view';

  // 데이터 로드
  useEffect(() => {
    async function loadCard() {
      setIsLoading(true);
      try {
        const result = await getCard(cardId);
        if (result.success && result.data) {
          setCard(result.data);
        } else {
          setError(result.error || '카드를 찾을 수 없습니다.');
        }
      } catch (err) {
        console.error('Failed to load card:', err);
        setError('카드 조회 중 오류가 발생했습니다.');
      } finally {
        setIsLoading(false);
      }
    }

    loadCard();
  }, [cardId]);

  // 수정 핸들러
  const handleSubmit = async (data: Record<string, unknown>) => {
    const result = await updateCard(cardId, data as Partial<CardFormData>);
    return { success: result.success, error: result.error };
  };

  // 삭제 핸들러
  const handleDelete = async () => {
    const result = await deleteCard(cardId);
    return { success: result.success, error: result.error };
  };

  // 에러 상태
  if (error && !isLoading) {
    return (
      <div className="p-6">
        <div className="text-center py-8 text-muted-foreground">
          {error}
        </div>
      </div>
    );
  }

  return (
    <IntegratedDetailTemplate
      config={cardConfig}
      mode={initialMode}
      initialData={card || undefined}
      itemId={cardId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
    />
  );
}
