import React, { useState, useEffect } from 'react';
import { Card, Button, Table, Space, Modal, Form, Input, Select, InputNumber, Tag, Steps, message, Popconfirm, Drawer, List, Checkbox, Radio, Empty, Spin, Typography, Row, Col } from 'antd';
import { PlusOutlined, CopyOutlined, EditOutlined, DeleteOutlined, EyeOutlined, ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import apiClient from '../../utils/request';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface PhaseItem {
  order: number;
  name: string;
  key?: string;
  type: 'serial' | 'parallel';
  depends: number[];
  sub_items: string[];
}

interface Template {
  id: number;
  name: string;
  description: string;
  phases: PhaseItem[];
  is_system: boolean;
  created_at: string;
}

const ProcessTemplates: React.FC = () => {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [viewDrawerVisible, setViewDrawerVisible] = useState(false);
  const [currentTemplate, setCurrentTemplate] = useState<Template | null>(null);
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  const [phases, setPhases] = useState<PhaseItem[]>([]);
  const [phaseDrawerVisible, setPhaseDrawerVisible] = useState(false);
  const [editingPhaseIndex, setEditingPhaseIndex] = useState<number>(-1);
  const [phaseForm] = Form.useForm();
  const [editingTemplateId, setEditingTemplateId] = useState<number | null>(null);

  useEffect(() => { fetchTemplates(); }, []);

  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const res = await apiClient.get('/process-templates');
      if (res.data.success) setTemplates(res.data.data);
    } catch (e) { message.error('获取模板列表失败'); }
    finally { setLoading(false); }
  };

  const handleCreate = () => {
    form.resetFields();
    setPhases([]);
    setCurrentStep(0);
    setEditingTemplateId(null);
    setCreateModalVisible(true);
  };

  const handleEdit = (t: Template) => {
    form.setFieldsValue({ name: t.name, description: t.description });
    setPhases(t.phases || []);
    setCurrentStep(1);
    setEditingTemplateId(t.id);
    setCreateModalVisible(true);
  };

  const handleCopy = async (t: Template) => {
    try {
      await apiClient.post(`/process-templates/${t.id}/copy`, { name: `${t.name} (副本)` });
      message.success('复制成功');
      fetchTemplates();
    } catch (e) { message.error('复制失败'); }
  };

  const handleDelete = async (id: number) => {
    try {
      await apiClient.delete(`/process-templates/${id}`);
      message.success('删除成功');
      fetchTemplates();
    } catch (e) { message.error('删除失败'); }
  };

  const handleView = (t: Template) => {
    setCurrentTemplate(t);
    setViewDrawerVisible(true);
  };

  const handleSaveTemplate = async () => {
    try {
      const name = form.getFieldValue('name');
      const description = form.getFieldValue('description');
      if (!name) { message.warning('请输入模板名称'); setCurrentStep(0); return; }
      if (phases.length === 0) { message.warning('请至少添加一个阶段'); setCurrentStep(1); return; }
      if (editingTemplateId) {
        await apiClient.put(`/process-templates/${editingTemplateId}`, { name, description, phases });
        message.success('模板更新成功');
      } else {
        await apiClient.post('/process-templates', { name, description, phases });
        message.success('模板创建成功');
      }
      setCreateModalVisible(false);
      setEditingTemplateId(null);
      fetchTemplates();
    } catch (e) { message.error('保存失败'); }
  };

  const addPhase = () => {
    setEditingPhaseIndex(-1);
    phaseForm.resetFields();
    phaseForm.setFieldsValue({ name: '', type: 'serial', sub_items_text: '', depends: [] });
    setPhaseDrawerVisible(true);
  };

  const editPhase = (index: number) => {
    setEditingPhaseIndex(index);
    const p = phases[index];
    phaseForm.setFieldsValue({
      name: p.name,
      type: p.type,
      sub_items_text: (p.sub_items || []).join('\n'),
      depends: p.depends.map(d => d),
    });
    setPhaseDrawerVisible(true);
  };

  const savePhase = () => {
    const values = phaseForm.getFieldsValue();
    const subItems = (values.sub_items_text || '').split('\n').map((s: string) => s.trim()).filter(Boolean);
    const phaseData: PhaseItem = {
      order: 0,
      name: values.name,
      type: values.type || 'serial',
      depends: values.depends || [],
      sub_items: subItems,
    };
    if (!phaseData.name) { message.warning('阶段名称不能为空'); return; }
    const newPhases = [...phases];
    if (editingPhaseIndex >= 0) {
      phaseData.order = newPhases[editingPhaseIndex].order;
      newPhases[editingPhaseIndex] = phaseData;
    } else {
      phaseData.order = newPhases.length + 1;
      newPhases.push(phaseData);
    }
    setPhases(newPhases);
    setPhaseDrawerVisible(false);
  };

  const removePhase = (index: number) => {
    const newPhases = phases.filter((_, i) => i !== index).map((p, i) => ({ ...p, order: i + 1 }));
    setPhases(newPhases);
  };

  const movePhase = (index: number, direction: 'up' | 'down') => {
    const newPhases = [...phases];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newPhases.length) return;
    [newPhases[index], newPhases[targetIndex]] = [newPhases[targetIndex], newPhases[index]];
    newPhases.forEach((p, i) => p.order = i + 1);
    setPhases(newPhases);
  };

  const getTypeTag = (type: string) => type === 'parallel' ? <Tag color="blue">并行</Tag> : <Tag color="green">串行</Tag>;

  const getDependsNames = (depends: number[]) => {
    return depends.map(d => {
      const p = phases.find(ph => ph.order === d);
      return p ? p.name : `阶段${d}`;
    }).join('、') || '无';
  };

  const columns = [
    { title: '模板名称', dataIndex: 'name', key: 'name', render: (text: string, r: Template) => <Space>{text}{r.is_system && <Tag color="gold">系统预设</Tag>}</Space> },
    { title: '阶段数', key: 'phases', render: (_: unknown, r: Template) => r.phases?.length || 0 },
    { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
    { title: '操作', key: 'action', render: (_: unknown, r: Template) => (
      <Space>
        <Button size="small" icon={<EyeOutlined />} onClick={() => handleView(r)}>查看</Button>
        <Button size="small" type="primary" icon={<EditOutlined />} onClick={() => handleEdit(r)}>编辑</Button>
        <Button size="small" icon={<CopyOutlined />} onClick={() => handleCopy(r)}>复制</Button>
        {!r.is_system && <Popconfirm title="确定删除？" onConfirm={() => handleDelete(r.id)}><Button size="small" danger icon={<DeleteOutlined />}>删除</Button></Popconfirm>}
      </Space>
    )},
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card title="工程模板管理" extra={<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>新建模板</Button>}>
        <Table columns={columns} dataSource={templates} rowKey="id" loading={loading} pagination={false} />
      </Card>

      <Modal title={editingTemplateId ? "编辑工程模板" : "新建工程模板"} open={createModalVisible} onCancel={() => setCreateModalVisible(false)} width={800} footer={[
        <Button key="cancel" onClick={() => setCreateModalVisible(false)}>取消</Button>,
        currentStep > 0 && <Button key="prev" onClick={() => setCurrentStep(currentStep - 1)}>上一步</Button>,
        currentStep < 2 && <Button key="next" type="primary" onClick={() => {
          if (currentStep === 0 && !form.getFieldValue('name')) { message.warning('请输入模板名称'); return; }
          setCurrentStep(currentStep + 1);
        }}>下一步</Button>,
        currentStep === 2 && <Button key="save" type="primary" onClick={handleSaveTemplate}>{editingTemplateId ? '保存修改' : '确认创建'}</Button>,
      ]}>
        <Steps current={currentStep} size="small" style={{ marginBottom: 24 }}>
          <Steps.Step title="基本信息" />
          <Steps.Step title="设计阶段" />
          <Steps.Step title="预览确认" />
        </Steps>

        {currentStep === 0 && (
          <Form form={form} layout="vertical">
            <Form.Item name="name" label="模板名称" rules={[{ required: true }]}>
              <Input placeholder="例如：配电安装工程" />
            </Form.Item>
            <Form.Item name="description" label="模板描述">
              <TextArea rows={3} placeholder="描述该模板适用的工程类型" />
            </Form.Item>
          </Form>
        )}

        {currentStep === 1 && (
          <div>
            {phases.length === 0 ? <Empty description="暂无阶段，请点击下方添加" /> : (
              <List bordered dataSource={phases} renderItem={(phase, index) => (
                <List.Item actions={[
                  <Button size="small" icon={<EditOutlined />} onClick={() => editPhase(index)}>编辑</Button>,
                  <Button size="small" icon={<ArrowUpOutlined />} onClick={() => movePhase(index, 'up')} disabled={index === 0} />,
                  <Button size="small" icon={<ArrowDownOutlined />} onClick={() => movePhase(index, 'down')} disabled={index === phases.length - 1} />,
                  <Popconfirm title="确定删除？" onConfirm={() => removePhase(index)}><Button size="small" danger icon={<DeleteOutlined />} /></Popconfirm>,
                ]}>
                  <List.Item.Meta
                    title={<Space>{phase.order}. {phase.name} {getTypeTag(phase.type)} <Text type="secondary">依赖：{getDependsNames(phase.depends)}</Text></Space>}
                    description={phase.sub_items?.length > 0 ? `子项：${phase.sub_items.join('、')}` : '无子项'}
                  />
                </List.Item>
              )} />
            )}
            <Button type="dashed" block icon={<PlusOutlined />} style={{ marginTop: 16 }} onClick={addPhase}>添加阶段</Button>
          </div>
        )}

        {currentStep === 2 && (
          <div>
            <Title level={5}>{form.getFieldValue('name')}</Title>
            <Paragraph type="secondary">{form.getFieldValue('description')}</Paragraph>
            <List bordered dataSource={phases} renderItem={(phase) => (
              <List.Item>
                <List.Item.Meta
                  title={<Space>{phase.order}. {phase.name} {getTypeTag(phase.type)}</Space>}
                  description={<>
                    <Text type="secondary">依赖：{getDependsNames(phase.depends)}</Text><br />
                    {phase.sub_items?.length > 0 && <Text>子项：{phase.sub_items.join('、')}</Text>}
                  </>}
                />
              </List.Item>
            )} />
          </div>
        )}
      </Modal>

      <Drawer title="阶段编辑" open={phaseDrawerVisible} onClose={() => setPhaseDrawerVisible(false)} width={400} extra={<Button type="primary" onClick={savePhase}>保存</Button>}>
        <Form form={phaseForm} layout="vertical">
          <Form.Item name="name" label="阶段名称" rules={[{ required: true }]}>
            <Input placeholder="例如：物资采购" />
          </Form.Item>
          <Form.Item name="type" label="阶段类型">
            <Radio.Group>
              <Radio value="serial">串行（必须等依赖项完成）</Radio>
              <Radio value="parallel">并行（可与相邻阶段同时进行）</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="depends" label="依赖关系（哪些阶段完成后才能开始）">
            <Checkbox.Group>
              {phases.filter((_, i) => i !== editingPhaseIndex).map(p => (
                <Checkbox key={p.order} value={p.order} style={{ display: 'block' }}>{p.order}. {p.name}</Checkbox>
              ))}
            </Checkbox.Group>
          </Form.Item>
          <Form.Item name="sub_items_text" label="子项列表（每行一个）">
            <TextArea rows={6} placeholder={"电杆采购\n变压器采购\n电缆采购"} />
          </Form.Item>
        </Form>
      </Drawer>

      <Drawer title={currentTemplate?.name} open={viewDrawerVisible} onClose={() => setViewDrawerVisible(false)} width={500}>
        {currentTemplate && (
          <div>
            <Paragraph type="secondary">{currentTemplate.description}</Paragraph>
            <List bordered dataSource={currentTemplate.phases || []} renderItem={(phase: PhaseItem) => (
              <List.Item>
                <List.Item.Meta
                  title={<Space>{phase.order}. {phase.name} {phase.type === 'parallel' ? <Tag color="blue">并行</Tag> : <Tag color="green">串行</Tag>}</Space>}
                  description={<>
                    <Text type="secondary">依赖：阶段{phase.depends?.join('、') || '无'}</Text><br />
                    {phase.sub_items?.length > 0 && <Text>子项：{phase.sub_items.join('、')}</Text>}
                  </>}
                />
              </List.Item>
            )} />
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default ProcessTemplates;
