import { useEffect, useState } from 'react';
import {
  Button,
  Form,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  DEV_PLAN_TASK_STATUS_LABELS,
  DEV_PLAN_TASK_TYPE_LABELS,
  type DevPlanTaskDto,
  type DevPlanTaskStatusDto,
  type DevPlanTaskTypeDto,
  type DevPlanVersionDto,
} from '@dukang/shared-types';
import { request } from '../lib/api';
import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';

const TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map((v) => ({
  value: v,
  label: DEV_PLAN_TASK_TYPE_LABELS[v],
}));

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

const STATUS_COLOR: Record<DevPlanTaskStatusDto, string> = {
  TODO: 'default',
  DEVELOPED: 'blue',
  RELEASED: 'green',
};

const DEFAULT_DISPATCH_SUPPLEMENT = '请按以下任务进入开发流程';

export default function DevPlanTasksPage() {
  const [filters, setFilters] = useState<Record<string, string>>({});
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [dispatchOpen, setDispatchOpen] = useState(false);
  const [batchEditOpen, setBatchEditOpen] = useState(false);
  const [batchSaving, setBatchSaving] = useState(false);
  const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
  const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
  const [saving, setSaving] = useState(false);
  const [dispatching, setDispatching] = useState(false);
  const [form] = Form.useForm();
  const [dispatchForm] = Form.useForm<{ supplement?: string }>();
  const [batchForm] = Form.useForm<{ status?: DevPlanTaskStatusDto; versionId?: string }>();

  useEffect(() => {
    if (!batchEditOpen) return;
    request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100')
      .then((res) => setVersions(res.items ?? []))
      .catch(() => setVersions([]));
  }, [batchEditOpen]);

  const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<DevPlanTaskDto>(
    '/admin/dev-plan/tasks',
    () => {
      const qs = new URLSearchParams();
      if (filters.status) qs.set('status', filters.status);
      if (filters.type) qs.set('type', filters.type);
      if (filters.keyword) qs.set('keyword', filters.keyword);
      return qs;
    },
    [filters],
  );

  function openCreate() {
    setEditing(null);
    form.setFieldsValue({ content: '', type: 'BUG', status: 'TODO' });
    setModalOpen(true);
  }

  function openEdit(row: DevPlanTaskDto) {
    setEditing(row);
    form.setFieldsValue({ content: row.content, type: row.type, status: row.status });
    setModalOpen(true);
  }

  async function save() {
    const values = await form.validateFields();
    setSaving(true);
    try {
      if (editing) {
        await request(`/admin/dev-plan/tasks/${editing.id}`, {
          method: 'PUT',
          body: JSON.stringify(values),
        });
        message.success('已更新');
      } else {
        await request('/admin/dev-plan/tasks', {
          method: 'POST',
          body: JSON.stringify({ content: values.content, type: values.type }),
        });
        message.success('已创建');
      }
      setModalOpen(false);
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '保存失败');
    } finally {
      setSaving(false);
    }
  }

  async function remove(id: string) {
    try {
      await request(`/admin/dev-plan/tasks/${id}`, { method: 'DELETE' });
      message.success('已删除');
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '删除失败');
    }
  }

  function openDispatch() {
    dispatchForm.setFieldsValue({
      supplement: DEFAULT_DISPATCH_SUPPLEMENT,
    });
    setDispatchOpen(true);
  }

  function openBatchEdit() {
    batchForm.setFieldsValue({ status: undefined, versionId: undefined });
    setBatchEditOpen(true);
  }

  async function submitBatchEdit() {
    const values = await batchForm.validateFields();
    if (!values.status && !values.versionId) {
      message.warning('请至少选择状态或关联版本');
      return;
    }
    setBatchSaving(true);
    try {
      await request('/admin/dev-plan/tasks/batch-update', {
        method: 'POST',
        body: JSON.stringify({
          taskIds: selectedRowKeys,
          status: values.status || undefined,
          versionId: values.versionId || undefined,
        }),
      });
      message.success('批量更新成功');
      setBatchEditOpen(false);
      setSelectedRowKeys([]);
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '批量更新失败');
    } finally {
      setBatchSaving(false);
    }
  }

  async function submitDispatch() {
    const values = await dispatchForm.validateFields();
    setDispatching(true);
    try {
      await request('/admin/dev-plan/tasks/dispatch', {
        method: 'POST',
        body: JSON.stringify({
          taskIds: selectedRowKeys,
          supplement: values.supplement?.trim() || undefined,
        }),
      });
      message.success('已派发到企微群');
      setDispatchOpen(false);
      setSelectedRowKeys([]);
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '派发失败');
    } finally {
      setDispatching(false);
    }
  }

  const columns: ColumnsType<DevPlanTaskDto> = [
    { title: '任务号', dataIndex: 'taskNo', width: 160 },
    {
      title: '类型',
      dataIndex: 'type',
      width: 80,
      render: (t: DevPlanTaskTypeDto) => DEV_PLAN_TASK_TYPE_LABELS[t],
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (s: DevPlanTaskStatusDto) => (
        <Tag color={STATUS_COLOR[s]}>{DEV_PLAN_TASK_STATUS_LABELS[s]}</Tag>
      ),
    },
    { title: '内容', dataIndex: 'content', ellipsis: true },
    { title: '来源工单', dataIndex: 'supportTicketNo', width: 140, render: (v) => v || '—' },
    { title: '创建人', dataIndex: 'creatorName', width: 90 },
    { title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作',
      width: 120,
      render: (_, row) => (
        <Space>
          <Button type="link" size="small" onClick={() => openEdit(row)}>
            编辑
          </Button>
          <Popconfirm title="确认删除？" onConfirm={() => void remove(row.id)}>
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Typography.Title level={4} style={{ margin: 0 }}>
          开发计划 · 任务列表
        </Typography.Title>
        <Space>
          <Button disabled={!selectedRowKeys.length} onClick={openBatchEdit}>
            批量编辑
          </Button>
          <Button disabled={!selectedRowKeys.length} onClick={openDispatch}>
            评审
          </Button>
          <Button type="primary" onClick={openCreate}>
            新建任务
          </Button>
        </Space>
      </div>

      <Form
        layout="inline"
        style={{ marginBottom: 16 }}
        onFinish={(v) => {
          setFilters(v);
          setPage(1);
        }}
      >
        <Form.Item name="type" label="类型">
          <Select allowClear style={{ width: 100 }} options={TYPE_OPTIONS} />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 100 }} options={STATUS_OPTIONS} />
        </Form.Item>
        <Form.Item name="keyword" label="关键词">
          <Input allowClear placeholder="任务号/内容" style={{ width: 160 }} />
        </Form.Item>
        <Button type="primary" htmlType="submit">
          筛选
        </Button>
      </Form>

      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={data?.items ?? []}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as string[]),
        }}
        scroll={{ x: 1100 }}
        pagination={{
          current: page,
          pageSize,
          total: data?.total ?? 0,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />

      <Modal
        title={editing ? '编辑任务' : '新建任务'}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={() => void save()}
        confirmLoading={saving}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="content" label="任务内容" rules={[{ required: true }]}>
            <Input.TextArea rows={4} maxLength={4000} showCount />
          </Form.Item>
          <Form.Item name="type" label="类型" rules={[{ required: true }]}>
            <Select options={TYPE_OPTIONS} />
          </Form.Item>
          {editing ? (
            <Form.Item name="status" label="状态" rules={[{ required: true }]}>
              <Select options={STATUS_OPTIONS} />
            </Form.Item>
          ) : null}
        </Form>
      </Modal>

      <Modal
        title="评审派发"
        open={dispatchOpen}
        onCancel={() => setDispatchOpen(false)}
        onOk={() => void submitDispatch()}
        confirmLoading={dispatching}
        destroyOnClose
      >
        <Typography.Paragraph type="secondary">
          已选 {selectedRowKeys.length} 条任务，将通过「企微机器人 → 消息推送」中勾选「开发任务评审派发」的实例推送到开发群（@
          userid 由各推送配置）。
        </Typography.Paragraph>
        <Form form={dispatchForm} layout="vertical">
          <Form.Item name="supplement" label="补充说明">
            <Input.TextArea rows={3} placeholder="默认任务说明；@ 成员由消息推送配置决定" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="批量编辑任务"
        open={batchEditOpen}
        onCancel={() => setBatchEditOpen(false)}
        onOk={() => void submitBatchEdit()}
        confirmLoading={batchSaving}
        destroyOnClose
      >
        <Typography.Paragraph type="secondary">已选 {selectedRowKeys.length} 条任务</Typography.Paragraph>
        <Form form={batchForm} layout="vertical">
          <Form.Item name="status" label="状态（不修改请留空）">
            <Select allowClear placeholder="不修改" options={STATUS_OPTIONS} />
          </Form.Item>
          <Form.Item name="versionId" label="关联版本（追加关联，不修改请留空）">
            <Select
              allowClear
              placeholder="不修改"
              options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
