import React, { useState, useEffect } from 'react';
import { Table, Button, Drawer, Form, Input, Space, message, Popconfirm } from 'antd';
import { PlusOutlined, DeleteOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';
import { supabase } from '@/config/supabase';

const UnitManagement = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingKey, setEditingKey] = useState('');
  const [form] = Form.useForm();

  // 获取单位数据
  const fetchUnits = async () => {
    setLoading(true);
    try {
      const { data: units, error } = await supabase
        .from('resources')
        .select('*')
        .eq('type', 'units')
        .order('created_at', { ascending: false });

      if (error) throw error;
      setData(units || []);
    } catch (error) {
      message.error('获取单位数据失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (drawerVisible) {
      fetchUnits();
    }
  }, [drawerVisible]);

  // 新增���位
  const handleAdd = () => {
    const newData = {
      id: Date.now().toString(),
      attributes: { name: '' },
      isNew: true
    };
    setData([newData, ...data]);
    setEditingKey(newData.id);
    form.setFieldsValue(newData.attributes);
  };

  // 保存单位数据
  const handleSave = async (record) => {
    try {
      const values = await form.validateFields();
      if (record.isNew) {
        // 新增
        const { error } = await supabase
          .from('resources')
          .insert([{
            type: 'units',
            attributes: {
              name: values.name
            },
            schema_version: 1
          }]);

        if (error) throw error;
      } else {
        // 更新
        const { error } = await supabase
          .from('resources')
          .update({
            attributes: {
              name: values.name
            },
            updated_at: new Date().toISOString()
          })
          .eq('id', record.id);

        if (error) throw error;
      }

      message.success('保存成功');
      setEditingKey('');
      fetchUnits();
    } catch (error) {
      message.error('保存失败');
      console.error(error);
    }
  };

  // 删除单位
  const handleDelete = async (id) => {
    try {
      const { error } = await supabase
        .from('resources')
        .delete()
        .eq('id', id);

      if (error) throw error;
      message.success('删除成功');
      fetchUnits();
    } catch (error) {
      message.error('删除失败');
      console.error(error);
    }
  };

  // 修改取消编辑的处理方法
  const handleCancel = (record) => {
    setEditingKey('');
    if (record.isNew) {
      // 如果是新增的记录，直接从数据中移除
      setData(data.filter(item => item.id !== record.id));
    }
    form.resetFields();
  };

  const columns = [
    {
      title: '单位名称',
      dataIndex: ['attributes', 'name'],
      width: '60%',
      render: (text, record) => {
        const isEditing = record.id === editingKey;
        return isEditing ? (
          <Form.Item
            name="name"
            rules={[{ required: true, message: '请输入单位名称!' }]}
            style={{ margin: 0 }}
            initialValue={text}
          >
            <Input placeholder="请输入单位名称" />
          </Form.Item>
        ) : (
          text
        );
      }
    },
    {
      title: '操作',
      width: '40%',
      render: (_, record) => {
        const isEditing = record.id === editingKey;
        return isEditing ? (
          <Space>
            <Button
              type="link"
              icon={<SaveOutlined />}
              onClick={() => handleSave(record)}
              className="text-green-600 hover:text-green-500"
            >
              保存
            </Button>
            <Button
              type="link"
              icon={<CloseOutlined />}
              onClick={() => handleCancel(record)}
              className="text-gray-600 hover:text-gray-500"
            >
              取消
            </Button>
          </Space>
        ) : (
          <Space>
            <Button
              type="link"
              disabled={editingKey !== ''}
              onClick={() => {
                setEditingKey(record.id);
                form.setFieldsValue(record.attributes);
              }}
              className="text-blue-600 hover:text-blue-500 disabled:text-gray-400"
            >
              编辑
            </Button>
            <Popconfirm
              title="确定要删除吗？"
              onConfirm={() => handleDelete(record.id)}
              okButtonProps={{ 
                className: "bg-red-500 hover:bg-red-600 border-red-500" 
              }}
            >
              <Button
                type="link"
                danger
                disabled={editingKey !== ''}
                icon={<DeleteOutlined />}
                className="text-red-600 hover:text-red-500 disabled:text-gray-400"
              />
            </Popconfirm>
          </Space>
        );
      }
    }
  ];

  return (
    <div>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => setDrawerVisible(true)}
        className="flex items-center"
      >
        单位管理
      </Button>

      <Drawer
        title={
          <span className="text-lg font-medium text-gray-800 dark:text-gray-200">
            单位管理
          </span>
        }
        placement="right"
        width={600}
        onClose={() => {
          setDrawerVisible(false);
          setEditingKey('');
          form.resetFields();
        }}
        open={drawerVisible}
        className="dark:bg-gray-800"
      >
        <div className="flex flex-col h-full">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            disabled={editingKey !== ''}
            className="mb-4 w-32 flex items-center justify-center"
          >
            新增单位
          </Button>

          <Form form={form} className="flex-1">
            <Table
              dataSource={data}
              columns={columns}
              rowKey="id"
              loading={loading}
              pagination={{
                pageSize: 10,
                className: "dark:text-gray-300"
              }}
              className="bg-white dark:bg-gray-800 rounded-lg shadow-sm"
              rowClassName={(record) => 
                `transition-colors ${
                  record.id === editingKey 
                    ? 'bg-blue-50 dark:bg-blue-900/20' 
                    : 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
                }`
              }
            />
          </Form>
        </div>
      </Drawer>
    </div>
  );
};

export default UnitManagement;
