'use client';

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

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

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);

  const urlMode = searchParams.get('mode');
  const initialMode: 'view' | 'edit' = 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 {
        setError('계좌 조회 중 오류가 발생했습니다.');
      } finally {
        setIsLoading(false);
      }
    }
    loadAccount();
  }, [accountId]);

  const handleSubmit = async (data: AccountFormData) => {
    const result = await updateBankAccount(accountId, data);
    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 (
    <AccountDetailForm
      mode={initialMode}
      initialData={account || undefined}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
    />
  );
}
