'use client';

/**
 * 계좌 상세/수정 페이지 - IntegratedDetailTemplate 적용
 */

import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { accountConfig } from '@/components/settings/AccountManagement/accountConfig';
import {
  getBankAccount,
  updateBankAccount,
  deleteBankAccount,
} from '@/components/settings/AccountManagement/actions';
import type { Account, AccountFormData } from '@/components/settings/AccountManagement/types';
import type { DetailMode } from '@/components/templates/IntegratedDetailTemplate';

export default function AccountDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const accountId = Number(params.id);

  const [account, setAccount] = useState<Account | 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 loadAccount() {
      setIsLoading(true);
      try {
        const result = await getBankAccount(accountId);
        if (result.success && result.data) {
          setAccount(result.data);
        } else {
          setError(result.error || '계좌를 찾을 수 없습니다.');
        }
      } catch (err) {
        console.error('Failed to load account:', err);
        setError('계좌 조회 중 오류가 발생했습니다.');
      } finally {
        setIsLoading(false);
      }
    }

    loadAccount();
  }, [accountId]);

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

  // 삭제 핸들러
  const handleDelete = async () => {
    const result = await deleteBankAccount(accountId);
    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={accountConfig}
      mode={initialMode}
      initialData={account || undefined}
      itemId={accountId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
      stickyButtons={true}
    />
  );
}
