import { useState } from 'react';
import {
  Button,
  Form,
  Input,
  Space,
  Popconfirm,
  Table,
  Tag,
  message,
} from 'antd';
import { PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  getSetting,
  updateSetting,
  deleteSetting,
} from '../../api/settings';
import { DrawerForm } from '../../components/DrawerForm';
import { useApiRequest } from '../../hooks/useApiRequest';
import { useThemeMode } from '../../hooks/useThemeMode';

interface SettingEntry {
  key: string;
  value: string;
  version: number;
}

export default function SystemSettings() {
  const [entries, setEntries] = useState<SettingEntry[]>([]);
  const [searchKey, setSearchKey] = useState('');
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editEntry, setEditEntry] = useState<SettingEntry | null>(null);
  const isDark = useThemeMode();
  const { execute } = useApiRequest();

  const handleSearch = async () => {
    if (!searchKey.trim()) {
      message.warning('请输入设置键名');
      return;
    }
    await execute(async () => {
      const result = await getSetting(searchKey.trim());
      const value = typeof result.setting_value === 'object' && result.setting_value !== null
        ? JSON.stringify(result.setting_value, null, 2)
        : String(result.setting_value ?? '');
      const version = result.version;
      setEntries((prev) => {
        const exists = prev.findIndex((e) => e.key === searchKey.trim());
        if (exists >= 0) {
          const updated = [...prev];
          updated[exists] = { ...updated[exists], value, version };
          return updated;
        }
        return [...prev, { key: searchKey.trim(), value, version }];
      });
    }, '查询成功', '查询失败');
  };

  const handleSave = async (values: Record<string, unknown>) => {
    const key = (values.setting_key as string).trim();
    const value = values.setting_value as string;
    try {
      JSON.parse(value);
    } catch {
      message.error('设置值必须是有效的 JSON 格式');
      return;
    }

    const editVersion = editEntry?.version;
    const jsonValue = JSON.parse(value);
    await execute(async () => {
      const result = await updateSetting(key, jsonValue, editVersion);
      const displayValue = typeof jsonValue === 'object' ? JSON.stringify(jsonValue, null, 2) : value;
      setEntries((prev) => {
        const exists = prev.findIndex((e) => e.key === key);
        if (exists >= 0) {
          const updated = [...prev];
          updated[exists] = { key, value: displayValue, version: result.version };
          return updated;
        }
        return [...prev, { key, value: displayValue, version: result.version }];
      });
    }, '设置已保存');

    setDrawerOpen(false);
    setEditEntry(null);
  };

  const handleDelete = async (key: string, version: number) => {
    await execute(() => deleteSetting(key, version), '设置已删除');
    setEntries((prev) => prev.filter((e) => e.key !== key));
  };

  const openCreate = () => {
    setEditEntry(null);
    setDrawerOpen(true);
  };

  const openEdit = (entry: SettingEntry) => {
    setEditEntry(entry);
    setDrawerOpen(true);
  };

  const columns = [
    {
      title: '键', dataIndex: 'key', key: 'key', width: 250,
      render: (v: string) => (
        <Tag style={{
          background: isDark ? '#0f172a' : '#f8fafc', border: 'none',
          color: isDark ? '#CBD5E1' : '#475569', fontFamily: 'monospace', fontSize: 12,
        }}>{v}</Tag>
      ),
    },
    {
      title: '值 (JSON)', dataIndex: 'value', key: 'value', ellipsis: true,
      render: (v: string) => <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{v}</span>,
    },
    {
      title: '操作', key: 'actions', width: 120,
      render: (_: unknown, record: SettingEntry) => (
        <Space size={4}>
          <Button size="small" type="text" icon={<EditOutlined />} onClick={() => openEdit(record)} style={{ color: isDark ? '#94a3b8' : '#475569' }} />
          <Popconfirm title="确定删除此设置？" onConfirm={() => handleDelete(record.key, record.version)}>
            <Button size="small" type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Space>
          <Input
            placeholder="输入设置键名查询"
            prefix={<SearchOutlined style={{ color: '#94a3b8' }} />}
            value={searchKey}
            onChange={(e) => setSearchKey(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 300, borderRadius: 8 }}
          />
          <Button onClick={handleSearch}>查询</Button>
        </Space>
        <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>添加设置</Button>
      </div>

      <div style={{
        background: isDark ? '#111827' : '#FFFFFF',
        borderRadius: 12,
        border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
        overflow: 'hidden',
      }}>
        <Table
          columns={columns}
          dataSource={entries}
          rowKey="key"
          size="small"
          pagination={false}
          locale={{ emptyText: '暂无设置项，请通过搜索查询或添加新设置' }}
        />
      </div>

      <DrawerForm
        title={editEntry ? '编辑设置' : '添加设置'}
        open={drawerOpen}
        onClose={() => { setDrawerOpen(false); setEditEntry(null); }}
        onSubmit={handleSave}
        initialValues={editEntry ? { setting_key: editEntry.key, setting_value: editEntry.value } : undefined}
        loading={false}
        width={560}
        columns={1}
      >
        <Form.Item name="setting_key" label="键名" rules={[{ required: true, message: '请输入设置键名' }]}>
          <Input disabled={!!editEntry} />
        </Form.Item>
        <Form.Item name="setting_value" label="值 (JSON)" rules={[{ required: true, message: '请输入设置值' }]}>
          <Input.TextArea rows={6} placeholder='{"key": "value"}' style={{ fontFamily: 'monospace' }} />
        </Form.Item>
      </DrawerForm>
    </div>
  );
}
