import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Switch, Tag, message, Space, Card, Typography } from 'antd';
import { PlusOutlined, EditOutlined, ReloadOutlined } from '@ant-design/icons';
import apiClient from '../../utils/request';

const { Title } = Typography;

const LEVEL1_OPTIONS = [
  { value: 'income', label: '收入', color: 'green' },
  { value: 'project', label: '项目支出', color: 'blue' },
  { value: 'company', label: '公司支出', color: 'orange' },
];

const ExpenseCategories: React.FC = () => {
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form] = Form.useForm();

  const fetchCategories = async () => {
    setLoading(true);
    try {
      const res = await apiClient.get('/expense-categories');
      if (res.data.success) {
        setCategories(res.data.data);
      }
    } catch (e) {
      message.error('获取分类失败');
    }
    setLoading(false);
  };

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

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: any) => {
    setEditingId(record.id);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      if (editingId) {
        await apiClient.put(`/expense-categories/${editingId}`, values);
        message.success('更新成功');
      } else {
        await apiClient.post('/expense-categories', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchCategories();
    } catch (e: any) {
      if (e.response?.data?.message) message.error(e.response.data.message);
    }
  };

  const handleToggleActive = async (id: number, isActive: boolean) => {
    try {
      await apiClient.put(`/expense-categories/${id}`, { is_active: isActive });
      message.success(isActive ? '已启用' : '已禁用');
      fetchCategories();
    } catch (e) {
      message.error('操作失败');
    }
  };

  const getLevel1Tag = (level1: string) => {
    const opt = LEVEL1_OPTIONS.find(o => o.value === level1);
    return <Tag color={opt?.color}>{opt?.label || level1}</Tag>;
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '一级分类', dataIndex: 'category_level1', width: 120, render: getLevel1Tag },
    { title: '二级编码', dataIndex: 'category_level2', width: 160 },
    { title: '显示名称', dataIndex: 'label', width: 140 },
    { title: '说明', dataIndex: 'description', ellipsis: true },
    { title: '排序', dataIndex: 'sort_order', width: 70 },
    {
      title: '状态', dataIndex: 'is_active', width: 90,
      render: (v: boolean, r: any) => (
        <Switch size="small" checked={v} onChange={(checked) => handleToggleActive(r.id, checked)} />
      )
    },
    {
      title: '操作', width: 100,
      render: (_: unknown, r: any) => (
        <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(r)}>编辑</Button>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Title level={4} style={{ margin: 0 }}>财务分类管理</Title>
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchCategories}>刷新</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增分类</Button>
          </Space>
        </div>
        <Table
          dataSource={categories}
          columns={columns}
          rowKey="id"
          loading={loading}
          pagination={false}
          size="small"
        />
      </Card>

      <Modal
        title={editingId ? '编辑分类' : '新增分类'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="category_level1" label="一级分类" rules={[{ required: true, message: '请选择' }]}>
            <Select options={LEVEL1_OPTIONS.map(o => ({ value: o.value, label: o.label }))} />
          </Form.Item>
          <Form.Item name="category_level2" label="二级编码" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="如 material, salary 等" />
          </Form.Item>
          <Form.Item name="label" label="显示名称" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="如 材料采购" />
          </Form.Item>
          <Form.Item name="description" label="说明">
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item name="sort_order" label="排序" initialValue={0}>
            <Input type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ExpenseCategories;
