import React, { useState } from 'react';
import { Card, Table, Button, Space, Modal, Form, DatePicker, InputNumber, message, Descriptions, Alert, Divider } from 'antd';
import { PlusOutlined, EyeOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { getSettlements, getSettlementDetail, getSettlementItems, generateSettlement, executeWeeklySettlement, previewWeeklySettlement } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import type { Settlement } from '@rent/shared-types';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';
import { SettlementStatusTag } from '@/components/SettlementStatusTag';

const { RangePicker } = DatePicker;

interface SettlementItem {
  id: number;
  orderId: number;
  orderAmount: number;
  platformFeeRate: number;
  platformFee: number;
  settlementAmount: number;
  orderCompletedAt: string;
}

interface PlatformSettlement extends Settlement {
  merchantName: string;
}

interface WeeklySettlementPreview {
  periodStart: string;
  periodEnd: string;
  totalOrders: number;
  totalAmount: number;
  totalServiceFee: number;
  totalSettlementAmount: number;
  merchants: Array<{
    merchantId: number;
    merchantName: string;
    orderCount: number;
    orderAmount: number;
    serviceFee: number;
    settlementAmount: number;
  }>;
}

const Settlements: React.FC = () => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [executing, setExecuting] = useState(false);
  const [previewData, setPreviewData] = useState<WeeklySettlementPreview | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  const {
    data: settlements,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    refresh,
  } = useTableData<PlatformSettlement>({
    fetchFn: async (params) => {
      const res = await getSettlements(params);
      return {
        list: res.data.items,
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 20)),
      };
    },
    initialParams: { pageSize: 20 },
  });

  const generateModal = useModal();
  const detailModal = useModal<PlatformSettlement>();
  const itemsModal = useModal<number>();
  const weeklyModal = useModal();
  const [items, setItems] = useState<SettlementItem[]>([]);
  const [itemsLoading, setItemsLoading] = useState(false);
  const [itemsPagination, setItemsPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  const handleViewDetail = async (settlement: PlatformSettlement) => {
    detailModal.open(settlement);
  };

  const handleViewItems = async (id: number, page = 1, pageSize = 10) => {
    setItemsLoading(true);
    try {
      const res = await getSettlementItems(id, { page, pageSize });
      setItems(res.data.items);
      setItemsPagination({ current: page, pageSize, total: res.data.total });
      itemsModal.open(id);
    } catch (error) {
      message.error('获取结算明细失败');
    } finally {
      setItemsLoading(false);
    }
  };

  const handleGenerate = async (values: any) => {
    setSubmitting(true);
    try {
      await generateSettlement(values.merchantId, {
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
      });
      message.success('结算单生成成功');
      generateModal.close();
      form.resetFields();
      refresh();
    } catch (error: any) {
      message.error(error.response?.data?.message || '生成失败');
    } finally {
      setSubmitting(false);
    }
  };

  const handlePreviewWeekly = async () => {
    setPreviewLoading(true);
    try {
      const res = await previewWeeklySettlement();
      setPreviewData(res.data);
      weeklyModal.open();
    } catch (error: any) {
      message.error(error.response?.data?.message || error.message || '获取预览数据失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  const handleExecuteWeekly = async () => {
    Modal.confirm({
      title: '确认执行周结算',
      content: '确定要执行周结算吗？此操作将为所有商家生成上周的结算单并转账。',
      okText: '确认执行',
      cancelText: '取消',
      onOk: async () => {
        setExecuting(true);
        try {
          await executeWeeklySettlement();
          message.success('周结算执行成功');
          weeklyModal.close();
          refresh();
        } catch (error: any) {
          message.error(error.response?.data?.message || error.message || '执行失败');
        } finally {
          setExecuting(false);
        }
      },
    });
  };

  const columns: ColumnsType<PlatformSettlement> = [
    {
      title: '结算ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '商家ID',
      dataIndex: 'merchantId',
      key: 'merchantId',
      width: 100,
    },
    {
      title: '商家名称',
      dataIndex: 'merchantName',
      key: 'merchantName',
      width: 200,
    },
    {
      title: '结算周期',
      key: 'period',
      width: 200,
      render: (_, record) => `${record.periodStart} ~ ${record.periodEnd}`,
    },
    {
      title: '订单数',
      dataIndex: 'orderCount',
      key: 'orderCount',
      width: 100,
    },
    {
      title: '订单总额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '平台服务费',
      dataIndex: 'serviceFee',
      key: 'serviceFee',
      width: 120,
      render: (fee: number) => <span style={{ color: '#52c41a' }}>+{formatMoney(fee, '')}</span>,
    },
    {
      title: '结算金额',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      width: 120,
      render: (amount: number) => (
        <span style={{ fontWeight: 'bold' }}>{formatMoney(amount)}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => <SettlementStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: PlatformSettlement) => (
        <Space>
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            详情
          </Button>
          <Button type="link" size="small" onClick={() => handleViewItems(record.id)}>
            明细
          </Button>
        </Space>
      ),
    },
  ];

  const itemColumns: ColumnsType<SettlementItem> = [
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 100,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '服务费率',
      dataIndex: 'platformFeeRate',
      key: 'platformFeeRate',
      width: 100,
      render: (rate: number) => `${(rate * 100).toFixed(1)}%`,
    },
    {
      title: '服务费',
      dataIndex: 'platformFee',
      key: 'platformFee',
      width: 120,
      render: (fee: number) => <span style={{ color: '#52c41a' }}>{formatMoney(fee)}</span>,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementAmount',
      key: 'settlementAmount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '订单完成时间',
      dataIndex: 'orderCompletedAt',
      key: 'orderCompletedAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>结算管理</h2>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => generateModal.open()}>
              生成结算单
            </Button>
            <Button
              type="primary"
              icon={<ThunderboltOutlined />}
              onClick={handlePreviewWeekly}
              loading={previewLoading}
            >
              执行周结算
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={settlements}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      <Modal
        title="生成结算单"
        open={generateModal.visible}
        onCancel={() => {
          generateModal.close();
          form.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleGenerate}>
          <Form.Item
            name="merchantId"
            label="商家ID"
            rules={[{ required: true, message: '请输入商家ID' }]}
          >
            <InputNumber style={{ width: '100%' }} placeholder="请输入商家ID" min={1} />
          </Form.Item>
          <Form.Item
            name="dateRange"
            label="结算周期"
            rules={[{ required: true, message: '请选择结算周期' }]}
          >
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => generateModal.close()}>取消</Button>
              <Button type="primary" htmlType="submit" loading={submitting}>
                生成
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="结算详情"
        open={detailModal.visible}
        onCancel={detailModal.close}
        footer={null}
        width={600}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="结算ID">{detailModal.data.id}</Descriptions.Item>
            <Descriptions.Item label="商家">
              {detailModal.data.merchantName} (ID: {detailModal.data.merchantId})
            </Descriptions.Item>
            <Descriptions.Item label="结算周期">
              {detailModal.data.periodStart} ~ {detailModal.data.periodEnd}
            </Descriptions.Item>
            <Descriptions.Item label="订单数量">{detailModal.data.orderCount} 笔</Descriptions.Item>
            <Descriptions.Item label="订单总额">{formatMoney(detailModal.data.totalAmount)}</Descriptions.Item>
            <Descriptions.Item label="平台服务费">
              <span style={{ color: '#52c41a' }}>{formatMoney(detailModal.data.serviceFee)}</span>
            </Descriptions.Item>
            <Descriptions.Item label="结算金额">
              <span style={{ fontWeight: 'bold' }}>
                {formatMoney(detailModal.data.actualAmount)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <SettlementStatusTag status={detailModal.data.status} />
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{formatDateTime(detailModal.data.createdAt)}</Descriptions.Item>
            {detailModal.data.paidAt && (
              <Descriptions.Item label="打款时间">{formatDateTime(detailModal.data.paidAt)}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      <Modal
        title="结算明细"
        open={itemsModal.visible}
        onCancel={itemsModal.close}
        footer={null}
        width={900}
      >
        <Table
          columns={itemColumns}
          dataSource={items}
          rowKey="id"
          loading={itemsLoading}
          pagination={{
            ...itemsPagination,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              if (itemsModal.data) {
                handleViewItems(itemsModal.data, page, pageSize);
              }
            },
          }}
        />
      </Modal>

      <Modal
        title="执行周结算"
        open={weeklyModal.visible}
        onCancel={weeklyModal.close}
        footer={null}
        width={900}
      >
        {previewData && (
          <>
            <Alert
              message="结算周期"
              description={`${previewData.periodStart} ~ ${previewData.periodEnd}`}
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />

            <Descriptions column={2} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="订单总数">{previewData.totalOrders} 笔</Descriptions.Item>
              <Descriptions.Item label="订单总额">{formatMoney(previewData.totalAmount)}</Descriptions.Item>
              <Descriptions.Item label="服务费总额">
                <span style={{ color: '#52c41a' }}>{formatMoney(previewData.totalServiceFee)}</span>
              </Descriptions.Item>
              <Descriptions.Item label="结算总额">
                <span style={{ fontWeight: 'bold' }}>{formatMoney(previewData.totalSettlementAmount)}</span>
              </Descriptions.Item>
            </Descriptions>

            <Divider>商家结算明细</Divider>

            {previewData.merchants.length === 0 ? (
              <Alert message="没有需要结算的订单" type="warning" showIcon />
            ) : (
              <>
                <Table
                  dataSource={previewData.merchants}
                  rowKey="merchantId"
                  pagination={false}
                  size="small"
                  columns={[
                    {
                      title: '商家ID',
                      dataIndex: 'merchantId',
                      key: 'merchantId',
                      width: 100,
                    },
                    {
                      title: '商家名称',
                      dataIndex: 'merchantName',
                      key: 'merchantName',
                      width: 200,
                    },
                    {
                      title: '订单数',
                      dataIndex: 'orderCount',
                      key: 'orderCount',
                      width: 100,
                    },
                    {
                      title: '订单总额',
                      dataIndex: 'orderAmount',
                      key: 'orderAmount',
                      width: 120,
                      render: (amount: number) => formatMoney(amount),
                    },
                    {
                      title: '服务费',
                      dataIndex: 'serviceFee',
                      key: 'serviceFee',
                      width: 120,
                      render: (fee: number) => <span style={{ color: '#52c41a' }}>{formatMoney(fee)}</span>,
                    },
                    {
                      title: '结算金额',
                      dataIndex: 'settlementAmount',
                      key: 'settlementAmount',
                      width: 120,
                      render: (amount: number) => (
                        <span style={{ fontWeight: 'bold' }}>{formatMoney(amount)}</span>
                      ),
                    },
                  ]}
                />

                <div style={{ marginTop: 16, textAlign: 'right' }}>
                  <Space>
                    <Button onClick={weeklyModal.close}>取消</Button>
                    <Button type="primary" onClick={handleExecuteWeekly} loading={executing}>
                      确认执行结算
                    </Button>
                  </Space>
                </div>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default Settlements;
