import { Button, Card, ErrorBlock, NavBar, Skeleton, Tag, Toast } from 'antd-mobile';
import { DownlandOutline } from 'antd-mobile-icons';
import { useQuery } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import { statementApi } from '@/api/statement';

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

  const { data, isLoading, error } = useQuery({
    queryKey: ['mobile.me.statement', id],
    queryFn: () => statementApi.detail(id),
    enabled: !isNaN(id),
    retry: false,
  });

  const forbidden = (error as { code?: string } | undefined)?.code === 'E403';
  const notFound = (error as { code?: string } | undefined)?.code === 'E404';

  const onDownload = async () => {
    try {
      const token = localStorage.getItem('mobile.accessToken');
      const res = await fetch(`/api/mobile/me/statements/${id}/download`, {
        headers: token ? { Authorization: `Bearer ${token}` } : undefined,
      });
      if (!res.ok) {
        Toast.show({ icon: 'fail', content: `다운로드 실패 (${res.status})` });
        return;
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `수수료명세서_${id}.xlsx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (e) {
      Toast.show({ icon: 'fail', content: '다운로드 중 오류가 발생했습니다' });
    }
  };

  return (
    <div className="page">
      <NavBar onBack={() => navigate(-1)}>명세서 상세</NavBar>
      <div style={{ padding: 12 }}>
        {isLoading && <Skeleton.Paragraph lineCount={6} animated />}
        {forbidden && <ErrorBlock status="empty" title="권한이 없습니다" description="본인 명세서가 아닙니다" />}
        {notFound && <ErrorBlock status="empty" title="명세서를 찾을 수 없습니다" />}
        {data && (
          <>
            <Card title={`${data.settleMonth} · ${data.statementTypeName ?? data.statementType}`}
                  extra={<Tag color={data.issueStatus === 'ISSUED' ? 'success' : 'warning'}>{data.issueStatusName ?? data.issueStatus ?? '-'}</Tag>}>
              <Row label="설계사" value={data.agentName ?? `#${data.agentId}`} />
              <Row label="발급일" value={data.issuedAt ?? '-'} />
            </Card>

            <Card title="금액 내역" style={{ marginTop: 12 }}>
              <Row label="총수수료" value={fmt(data.grossAmount)} />
              <Row label="소득세" value={fmt(data.incomeTaxAmount)} />
              <Row label="지방소득세" value={fmt(data.localTaxAmount)} />
              <Row label="부가세" value={fmt(data.vatAmount)} />
              <Row label="차감" value={fmt(data.deductionAmount)} />
              <Row label="실수령액" value={fmt(data.netAmount)} bold />
            </Card>

            {data.filePath && (
              <Button block color="primary" style={{ marginTop: 16 }} onClick={onDownload}>
                <DownlandOutline /> 엑셀 다운로드
              </Button>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function Row({ label, value, bold }: { label: string; value: string | number; bold?: boolean }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0' }}>
      <span style={{ color: '#666' }}>{label}</span>
      <span style={{ fontWeight: bold ? 700 : 400 }}>{value}</span>
    </div>
  );
}

function fmt(n?: number) {
  if (n == null) return '-';
  return `${n.toLocaleString()}원`;
}
