import { useEffect, useState } from 'react';
import {
  Button,
  Form,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  DEV_PLAN_VERSION_STATUS_LABELS,
  type DevPlanTaskDto,
  type DevPlanVersionDto,
  type DevPlanVersionStatusDto,
} 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 { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';



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

const STATUS_COLOR: Record<DevPlanVersionStatusDto, string> = {
  PENDING: 'default',
  IN_PROGRESS: 'processing',
  TESTING: 'purple',
  RELEASED: 'green',
  STOPPED: 'red',
};

function formatDuration(minutes?: number | null) {
  if (minutes == null) return '—';
  if (minutes < 60) return `${minutes} 分钟`;
  return `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分`;
}

export default function DevPlanVersionsPage() {
  const [filters, setFilters] = useState<Record<string, string>>({});
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<DevPlanVersionDto | null>(null);
  const [saving, setSaving] = useState(false);
  const [allTasks, setAllTasks] = useState<DevPlanTaskDto[]>([]);
  const [form] = Form.useForm();

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

  useEffect(() => {
    void request<{ items: DevPlanTaskDto[] }>('/admin/dev-plan/tasks?page=1&pageSize=500')
      .then((res) => setAllTasks(res.items ?? []))
      .catch(() => setAllTasks([]));
  }, []);

  async function openEdit(row: DevPlanVersionDto) {
    const detail = await request<DevPlanVersionDto>(`/admin/dev-plan/versions/${row.id}`);
    setEditing(detail);
    form.setFieldsValue({
      versionNo: detail.versionNo,
      content: detail.content ?? '',
      status: detail.status,
      taskIds: detail.taskIds ?? [],
    });
    setModalOpen(true);
  }

  function openCreate() {
    setEditing(null);
    form.setFieldsValue({ versionNo: '', content: '', status: 'PENDING', taskIds: [] });
    setModalOpen(true);
  }

  async function save() {
    const values = await form.validateFields();
    setSaving(true);
    try {
      const body = {
        versionNo: values.versionNo.trim(),
        content: values.content?.trim() || undefined,
        status: values.status,
        taskIds: values.taskIds ?? [],
      };
      if (editing) {
        await request(`/admin/dev-plan/versions/${editing.id}`, {
          method: 'PUT',
          body: JSON.stringify(body),
        });
        message.success('已更新');
      } else {
        await request('/admin/dev-plan/versions', { method: 'POST', body: JSON.stringify(body) });
        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/versions/${id}`, { method: 'DELETE' });
      message.success('已删除');
      reload();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '删除失败');
    }
  }

  const baseColumns: ColumnsType<DevPlanVersionDto> = [
    { title: '版本号', dataIndex: 'versionNo', width: 120, render: (v, row) => (
      <AdminPrimaryLink onClick={() => void openEdit(row)}>{v}</AdminPrimaryLink>
    ) },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (s: DevPlanVersionStatusDto) => (
        <Tag color={STATUS_COLOR[s]}>{DEV_PLAN_VERSION_STATUS_LABELS[s]}</Tag>
      ),
    },
    { title: '内容', dataIndex: 'content', render: (v) => v || '—' },
    { title: '开发起始', dataIndex: 'devStartedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
    { title: '开发完成', dataIndex: 'devCompletedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
    { title: '上线时间', dataIndex: 'releasedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
    {
      title: '用时',
      dataIndex: 'durationMinutes',
      width: 100,
      render: (v) => formatDuration(v),
    },
    { title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作',
      width: 120,
      render: (_, row) => (
        <Space>
          <Button type="link" size="small" onClick={() => void openEdit(row)}>
            编辑
          </Button>
          <Popconfirm title="确认删除？（不删除关联任务）" onConfirm={() => void remove(row.id)}>
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const { columns, settingsButton, settingsModal } = useAdminListColumns('dev-plan-versions', baseColumns, { page, pageSize });

  return (
    <div>
      {settingsModal}
      <AdminListHeader
        title="开发计划 · 版本列表"
        settings={settingsButton}
        actions={
          <Button type="primary" onClick={openCreate}>
            新建版本
          </Button>
        }
      />

      <Form
        layout="inline"
        style={{ marginBottom: 16 }}
        onFinish={(v) => {
          setFilters(v);
          setPage(1);
        }}
      >
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
        </Form.Item>
        <Form.Item name="keyword" label="查找">
          <Input allowClear placeholder="版本号或内容" style={{ width: 220 }} />
        </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);
          },
        }}
      />

      <Modal
        title={editing ? '编辑版本' : '新建版本'}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={() => void save()}
        confirmLoading={saving}
        destroyOnClose
        width={640}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="versionNo" label="版本号" rules={[{ required: true }]}>
            <Input placeholder="如 v3.4.11" maxLength={32} />
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true }]}>
            <Select options={STATUS_OPTIONS} />
          </Form.Item>
          <Form.Item name="content" label="内容">
            <Input.TextArea placeholder="版本描述 / 更新日志" rows={3} maxLength={500} showCount />
          </Form.Item>
          <Form.Item name="taskIds" label="关联任务">
            <Select
              mode="multiple"
              allowClear
              showSearch
              optionFilterProp="label"
              options={allTasks.map((t) => ({
                value: t.id,
                label: `${t.taskNo} · ${t.content.slice(0, 40)}`,
              }))}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
