import { useState } from 'react';
import {
  Button,
  Descriptions,
  Drawer,
  Form,
  Image,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  TICKET_STATUS_LABELS,
  TICKET_TYPE_LABELS,
  ticketStatusLabel,
  type TicketStatusDto,
  type TicketTypeDto,
} from '@dukang/shared-types';
import { request } from '../lib/api';
import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';


type Row = {
  id: string;
  ticketNo: string;
  ticketType: TicketTypeDto;
  status: string;
  refType: string;
  refId: string;
  remark?: string;
  extraJson?: { evidenceUrls?: string[] };
  createdAt: string;
};

const STATUS_COLOR: Partial<Record<TicketStatusDto, string>> = {
  PENDING: 'orange',
  OPEN: 'blue',
  COLLABORATING: 'cyan',
  RESOLVED: 'green',
  REJECTED: 'red',
  COMPLETED: 'green',
  CLOSED: 'default',
};

const STATUS_OPTIONS = (Object.keys(TICKET_STATUS_LABELS) as TicketStatusDto[]).map((value) => ({
  value,
  label: TICKET_STATUS_LABELS[value],
}));

export default function TicketsPage() {
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
    '/admin/tickets',
    () => {
      const qs = new URLSearchParams();
      if (filters.ticketType) qs.set('ticketType', filters.ticketType);
      if (filters.status) qs.set('status', filters.status);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Row | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [createForm] = Form.useForm<{
    ticketType: TicketTypeDto;
    orderNo: string;
    remark?: string;
  }>();

  async function approve(id: string) {
    await request(`/admin/tickets/${id}/approve`, { method: 'POST', body: JSON.stringify({}) });
    message.success('已审批通过');
    reload();
    setDrawerOpen(false);
  }

  async function reject(id: string) {
    await request(`/admin/tickets/${id}/reject`, {
      method: 'POST',
      body: JSON.stringify({ remark: '驳回' }),
    });
    message.success('已驳回');
    reload();
    setDrawerOpen(false);
  }

  async function submitCreate() {
    const values = await createForm.validateFields();
    setCreating(true);
    try {
      await request('/admin/tickets', {
        method: 'POST',
        body: JSON.stringify({
          ticketType: values.ticketType,
          orderNo: values.orderNo.trim(),
          remark: values.remark?.trim() || undefined,
        }),
      });
      message.success('工单已创建');
      setCreateOpen(false);
      createForm.resetFields();
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '创建失败');
    } finally {
      setCreating(false);
    }
  }

  const baseColumns: ColumnsType<Row> = [
    {
      title: '工单号',
      dataIndex: 'ticketNo',
      width: 180,
      render: (v, row) => (
        <AdminPrimaryLink
          onClick={async () => {
            setDetail(await request(`/admin/tickets/${row.id}`));
            setDrawerOpen(true);
          }}
        >
          {v}
        </AdminPrimaryLink>
      ),
    },
    {
      title: '类型',
      dataIndex: 'ticketType',
      width: 110,
      render: (t: TicketTypeDto) => TICKET_TYPE_LABELS[t] ?? t,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (s: string) => (
        <Tag color={STATUS_COLOR[s as TicketStatusDto] ?? 'default'}>{ticketStatusLabel(s)}</Tag>
      ),
    },
    { title: '关联', width: 140, render: (_, r) => `${r.refType}#${r.refId}` },
    { title: '备注', dataIndex: 'remark' },
    { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作',
      width: 80,
      render: (_, row) => (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            setDetail(await request(`/admin/tickets/${row.id}`));
            setDrawerOpen(true);
          }}
        >
          详情
        </Button>
      ),
    },
  ];

  const evidenceUrls = detail?.extraJson?.evidenceUrls ?? [];

  const { columns, settingsButton, settingsModal } = useAdminListColumns('tickets', baseColumns, { page, pageSize });

  return (
    <div>
      {settingsModal}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <Typography.Title level={4} style={{ margin: 0 }}>
          工单中心
        </Typography.Title>
          {settingsButton}
        <Button type="primary" onClick={() => setCreateOpen(true)}>
          创建工单
        </Button>
      </div>
      <Form
        layout="inline"
        style={{ marginBottom: 16 }}
        onFinish={(v) => {
          setFilters(v);
          setPage(1);
        }}
      >
        <Form.Item name="ticketType" label="类型">
          <Select
            allowClear
            style={{ width: 140 }}
            options={[
              { value: 'REFUND', label: '仅退款' },
              { value: 'RESHIPMENT', label: '破损补发' },
              { value: 'DAMAGE_RETURN', label: '破损退货' },
              { value: 'RETURN_REFUND', label: '退货退款' },
              { value: 'PACKAGE_DISPUTE', label: '套餐异议' },
              { value: 'ALERT', label: '异常' },
            ]}
          />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 140 }} placeholder="全部" options={STATUS_OPTIONS} />
        </Form.Item>
        <Button type="primary" htmlType="submit">
          筛选
        </Button>
      </Form>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={data?.items ?? []}
        scroll={{ x: 'max-content' }}
        pagination={{
          current: page,
          pageSize,
          total: data?.total ?? 0,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
      <Drawer
        title="工单详情"
        width={480}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        extra={
          detail && (detail.status === 'PENDING' || detail.status === 'OPEN') ? (
            <Space>
              <Button type="primary" onClick={() => approve(String(detail.id))}>
                通过
              </Button>
              <Button danger onClick={() => reject(String(detail.id))}>
                驳回
              </Button>
            </Space>
          ) : null
        }
      >
        {detail && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="工单号">{String(detail.ticketNo)}</Descriptions.Item>
            <Descriptions.Item label="类型">
              {TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={STATUS_COLOR[detail.status as TicketStatusDto] ?? 'default'}>
                {ticketStatusLabel(detail.status)}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="关联">
              {String(detail.refType)} #{String(detail.refId)}
            </Descriptions.Item>
            <Descriptions.Item label="备注">{String(detail.remark ?? '—')}</Descriptions.Item>
            <Descriptions.Item label="凭证">
              {evidenceUrls.length ? (
                <Image.PreviewGroup>
                  {evidenceUrls.map((url) => (
                    <Image key={url} src={url} width={72} style={{ marginRight: 8 }} />
                  ))}
                </Image.PreviewGroup>
              ) : (
                '—'
              )}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>

      <Modal
        title="创建工单"
        open={createOpen}
        onCancel={() => setCreateOpen(false)}
        onOk={() => void submitCreate()}
        confirmLoading={creating}
        destroyOnClose
        okText="提交"
      >
        <Form form={createForm} layout="vertical" initialValues={{ ticketType: 'REFUND' }}>
          <Form.Item
            name="ticketType"
            label="工单类型"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select
              options={[
                { value: 'REFUND', label: '仅退款' },
                { value: 'RESHIPMENT', label: '破损补发' },
                { value: 'DAMAGE_RETURN', label: '破损退货' },
                { value: 'RETURN_REFUND', label: '退货退款' },
                { value: 'ALERT', label: '异常' },
              ]}
            />
          </Form.Item>
          <Form.Item
            name="orderNo"
            label="订单号"
            rules={[{ required: true, message: '请填写订单号' }]}
          >
            <Input placeholder="关联订单号" allowClear />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="可选" maxLength={512} showCount />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
