import { Button, Card, Col, Descriptions, Row, Space, Statistic } from 'antd';
import { useQuery } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import { agentApi } from '@/api/agent';

export default function AgentDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const { data, isLoading } = useQuery({
    queryKey: ['agent', 'detail', id],
    queryFn: () => agentApi.detail(Number(id)),
    enabled: !!id,
  });

  return (
    <PageContainer
      title={data ? `설계사 — ${data.agentName}` : '설계사 상세'}
      extra={
        <Space>
          <PermissionButton menuCode="ORG_AGENT" permCode="UPDATE" type="primary"
                            onClick={() => navigate(`/org/agents/${id}/edit`)}>
            수정
          </PermissionButton>
          <Button onClick={() => navigate(-1)}>목록</Button>
        </Space>
      }
    >
      {isLoading || !data ? null : (
        <>
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={6}><Card><Statistic title="계약 수" value={data.contractCount ?? 0} suffix="건" /></Card></Col>
            <Col span={6}>
              <Card>
                <Statistic title="누적 수수료" valueRender={() =>
                  <MoneyText value={data.totalCommission} />
                } />
              </Card>
            </Col>
            <Col span={6}><Card><Statistic title="소속" value={data.orgName ?? '-'} /></Card></Col>
            <Col span={6}><Card><Statistic title="직급" value={data.gradeName ?? '-'} /></Card></Col>
          </Row>

          <Card title="기본 정보">
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="설계사명">{data.agentName}</Descriptions.Item>
              <Descriptions.Item label="사번">{data.licenseNo ?? '-'}</Descriptions.Item>
              <Descriptions.Item label="전화번호">{data.phone ?? '-'}</Descriptions.Item>
              <Descriptions.Item label="이메일">{data.email ?? '-'}</Descriptions.Item>
              <Descriptions.Item label="입사일">{data.joinDate ?? '-'}</Descriptions.Item>
              <Descriptions.Item label="상태">
                <CodeBadge groupCode="AGENT_STATUS" value={data.status} />
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </>
      )}
    </PageContainer>
  );
}
