import React, { useState } from 'react';
import { Modal, Tabs } from 'antd';
import { App } from 'antd';
import ClientInfoTab from './client-detail/ClientInfoTab';
import ContactsTab from './client-detail/ContactsTab';
import ContractsTab from './client-detail/ContractsTab';
import ExpensesTab from './client-detail/ExpensesTab';
import FilesTab from './client-detail/FilesTab';
import LogsTab from './client-detail/LogsTab';
import { useQuery } from '@tanstack/react-query';
import { clientClient } from '@/client/api';
import type { InferResponseType } from 'hono/client';

const { TabPane } = Tabs;

interface ClientDetailModalProps {
  clientId: number | null;
  visible: boolean;
  onClose: () => void;
}

const ClientDetailModal: React.FC<ClientDetailModalProps> = ({ clientId, visible, onClose }) => {
  const { message } = App.useApp();
  const [activeTab, setActiveTab] = useState('info');

  // 获取客户基本信息用于标题
  const { data: clientDetail } = useQuery({
    queryKey: ['client', clientId],
    queryFn: async () => {
      if (!clientId) return null;
      const res = await clientClient[':id'].$get({ param: { id: clientId } });
      if (!res.ok) throw new Error('获取客户详情失败');
      return res.json();
    },
    enabled: !!clientId,
  });

  const clientName = clientDetail?.companyName || '客户详情';

  return (
    <Modal
      title={`${clientName} - 详情`}
      open={visible}
      onCancel={onClose}
      footer={null}
      width={1000}
      className="client-detail-modal"
      destroyOnClose
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        tabPosition="top"
        items={[
          {
            key: 'info',
            label: '客户档案',
            children: clientId ? <ClientInfoTab clientId={clientId} /> : null,
          },
          {
            key: 'contacts',
            label: '相关联系人',
            children: clientId ? <ContactsTab clientId={clientId} /> : null,
          },
          {
            key: 'contracts',
            label: '合同记录',
            children: clientId ? <ContractsTab clientId={clientId} /> : null,
          },
          {
            key: 'expenses',
            label: '费用记录',
            children: clientId ? <ExpensesTab clientId={clientId} /> : null,
          },
          {
            key: 'files',
            label: '文件记录',
            children: clientId ? <FilesTab clientId={clientId} /> : null,
          },
          {
            key: 'logs',
            label: '操作记录',
            children: clientId ? <LogsTab clientId={clientId} /> : null,
          },
        ]}
      />
    </Modal>
  );
};

export default ClientDetailModal;