import {
  Button,
  Drawer,
  Form,
  Input,
  message,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  Card,
  Switch,
  Tooltip,
  Row,
  Col
} from "antd";
import { useEffect, useState, useCallback } from "react";
import { useTranslation } from "react-i18next";
import {
  pageParams,
  createParam,
  updateParam,
  deleteParam
} from "../api";
import { usePermission } from "../hooks/usePermission";
import { useDict } from "../hooks/useDict";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  SettingOutlined,
  InfoCircleOutlined
} from "@ant-design/icons";
import type { SysParamVO, SysParamQuery } from "../types";
import PageHeader from "../components/shared/PageHeader";
import "./SysParams.css";

const { Title, Text } = Typography;

export default function SysParams() {
  const { t } = useTranslation();
  const { can } = usePermission();

  // Dictionaries
  const { items: statusDict } = useDict("sys_common_status");
  const { items: paramTypeDict } = useDict("sys_param_type");
  
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [data, setData] = useState<SysParamVO[]>([]);
  const [total, setTotal] = useState(0);
  
  const [queryParams, setQueryParams] = useState<SysParamQuery>({
    pageNum: 1,
    pageSize: 10
  });

  // Drawer state
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editing, setEditing] = useState<SysParamVO | null>(null);
  const [form] = Form.useForm();

  const loadData = useCallback(async (query = queryParams) => {
    setLoading(true);
    try {
      const res = await pageParams(query);
      setData(res.records || []);
      setTotal(res.total || 0);
    } finally {
      setLoading(false);
    }
  }, [queryParams]);

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

  const handleSearch = (values: any) => {
    const newQuery = { ...queryParams, ...values, pageNum: 1 };
    setQueryParams(newQuery);
  };

  const handleReset = () => {
    form.resetFields();
    const newQuery = { pageNum: 1, pageSize: 10 };
    setQueryParams(newQuery);
  };

  const handlePageChange = (page: number, pageSize: number) => {
    setQueryParams(prev => ({ ...prev, pageNum: page, pageSize }));
  };

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ isSystem: false, status: 1 });
    setDrawerOpen(true);
  };

  const openEdit = (record: SysParamVO) => {
    setEditing(record);
    form.setFieldsValue(record);
    setDrawerOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteParam(id);
      message.success(t('common.success'));
      loadData();
    } catch (e) {
      // Handled by global interceptor
    }
  };

  const submit = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);
      
      if (editing) {
        await updateParam(editing.paramId, values);
      } else {
        await createParam(values);
      }

      message.success(t('common.success'));
      setDrawerOpen(false);
      loadData();
    } catch (e) {
      // Form validation errors or API errors
    } finally {
      setSaving(false);
    }
  };

  const columns = [
    {
      title: t('sysParams.paramKey'),
      dataIndex: "paramKey",
      key: "paramKey",
      render: (text: string, record: SysParamVO) => (
        <Space direction="vertical" size={0}>
          <Text className="param-key-text">{text}</Text>
          {record.isSystem === 1 && (
            <Tag color="orange" size={0} style={{ fontSize: 10, marginTop: 2, padding: '0 4px' }}>
              {t('sysParams.isSystem')}
            </Tag>
          )}
        </Space>
      ),
    },
    {
      title: t('sysParams.paramValue'),
      dataIndex: "paramValue",
      key: "paramValue",
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <Text code>{text}</Text>
        </Tooltip>
      ),
    },
    {
      title: t('sysParams.paramType'),
      dataIndex: "paramType",
      key: "paramType",
      width: 120,
      render: (type: string) => <Tag className="param-type-tag">{type || 'DEFAULT'}</Tag>
    },
    {
      title: t('sysParams.description'),
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
    {
      title: t('common.status'),
      dataIndex: "status",
      width: 80,
      render: (status: number) => {
        const item = statusDict.find(i => i.itemValue === String(status));
        return (
          <Tag color={status === 1 ? "green" : "red"}>
            {item ? item.itemLabel : (status === 1 ? "正常" : "禁用")}
          </Tag>
        );
      },
    },
    {
      title: t('common.action'),
      key: "action",
      width: 110,
      fixed: "right" as const,
      render: (_: any, record: SysParamVO) => (
        <Space>
          {can("sys_param:update") && (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => openEdit(record)}
            />
          )}
          {can("sys_param:delete") && record.isSystem !== 1 && (
            <Popconfirm title="确定删除该参数吗？" onConfirm={() => handleDelete(record.paramId)}>
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="sys-params-page p-6">
      <PageHeader
        title={t('sysParams.title')}
        subtitle={t('sysParams.subtitle')}
        extra={can("sys_param:create") && (
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            {t('common.create')}
          </Button>
        )}
      />

      <Card className="sys-params-table-card shadow-sm mb-4">
        <Form
          layout="inline"
          onFinish={handleSearch}
          className="mb-4"
        >
          <Form.Item name="paramKey">
            <Input
              placeholder={t('sysParams.paramKey')}
              prefix={<SearchOutlined />}
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item name="paramType">
            <Select
              placeholder={t('sysParams.paramType')}
              allowClear
              style={{ width: 150 }}
              options={paramTypeDict.map(i => ({ label: i.itemLabel, value: i.itemValue }))}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {t('common.search')}
              </Button>
              <Button onClick={handleReset}>
                {t('common.reset')}
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          rowKey="paramId"
          columns={columns}
          dataSource={data}
          loading={loading}
          size="middle"
          pagination={{
            current: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            total: total,
            showTotal: (tTotal) => t('common.total', { total: tTotal }),
            onChange: handlePageChange,
            showSizeChanger: true,
          }}
        />
      </Card>

      <Drawer
        title={
          <span>
            <SettingOutlined className="mr-2" />
            {editing ? t('sysParams.drawerTitleEdit') : t('sysParams.drawerTitleCreate')}
          </span>
        }
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={500}
        destroyOnClose
        footer={
          <div className="flex justify-end gap-2 p-2">
            <Button onClick={() => setDrawerOpen(false)}>{t('common.cancel')}</Button>
            <Button type="primary" loading={saving} onClick={submit}>
              {t('common.save')}
            </Button>
          </div>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label={t('sysParams.paramKey')}
            name="paramKey"
            rules={[{ required: true, message: t('sysParams.paramKey') }]}
          >
            <Input placeholder="sys.config.example" disabled={!!editing} />
          </Form.Item>

          <Form.Item
            label={t('sysParams.paramValue')}
            name="paramValue"
            rules={[{ required: true, message: t('sysParams.paramValue') }]}
          >
            <Input.TextArea rows={4} placeholder="Enter parameter value" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('sysParams.paramType')}
                name="paramType"
                rules={[{ required: true, message: t('sysParams.paramType') }]}
              >
                <Select
                  options={paramTypeDict.map(i => ({ label: i.itemLabel, value: i.itemValue }))}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('common.status')}
                name="status"
                initialValue={1}
              >
                <Select
                  options={statusDict.map(i => ({ label: i.itemLabel, value: Number(i.itemValue) }))}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label={
              <Space>
                {t('sysParams.isSystem')}
                <Tooltip title="系统参数通常禁止删除，由开发者在代码中使用">
                  <InfoCircleOutlined style={{ color: '#8c8c8c' }} />
                </Tooltip>
              </Space>
            }
            name="isSystem"
            valuePropName="checked"
            getValueProps={(value) => ({ checked: value === 1 })}
            getValueFromEvent={(checked) => (checked ? 1 : 0)}
          >
            <Switch />
          </Form.Item>

          <Form.Item label={t('sysParams.description')} name="description">
            <Input.TextArea rows={3} placeholder="Describe the purpose of this parameter" />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
