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

const { Text } = Typography;

export default function SysParams() {
  const { t } = useTranslation();
  const { can } = usePermission();
  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 });
  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 response = await pageParams(query);
      setData(response.records || []);
      setTotal(response.total || 0);
    } finally {
      setLoading(false);
    }
  }, [queryParams]);

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

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

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

  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 {
    }
  };

  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();
    } 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" 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 || t("sysParamsExt.defaultType")}</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((dictItem) => dictItem.itemValue === String(status));
        return <Tag color={status === 1 ? "green" : "red"}>{item ? item.itemLabel : status === 1 ? t("sysParamsExt.enabled") : t("sysParamsExt.disabled")}</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={t("sysParamsExt.deleteConfirm")} okText={t("common.confirm")} cancelText={t("common.cancel")} onConfirm={() => handleDelete(record.paramId)}>
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          )}
        </Space>
      )
    }
  ];

  return (
    <div className="app-page sys-params-page">
      <PageHeader title={t("sysParams.title")} subtitle={t("sysParams.subtitle")} />

      <Card className="sys-params-table-card app-page__filter-card" styles={{ body: { padding: "16px" } }}>
        <div className="app-page__toolbar" style={{ justifyContent: "space-between", width: "100%" }}>
          <Form layout="inline" onFinish={handleSearch} className="app-page__toolbar">
            <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((item) => ({ label: item.itemLabel, value: item.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>
          {can("sys_param:create") && <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>{t("common.create")}</Button>}
        </div>
      </Card>

      <Card className="app-page__content-card flex-1 flex flex-col overflow-hidden" styles={{ body: { padding: 0, flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" } }}>
        <Table
          rowKey="paramId"
          columns={columns}
          dataSource={data}
          loading={loading}
          size="middle"
          scroll={{ y: "calc(100vh - 350px)" }}
          pagination={getStandardPagination(total, queryParams.pageNum || 1, queryParams.pageSize || 10, handlePageChange)}
        />
      </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="app-page__drawer-footer"><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={t("sysParamsExt.paramKeyPlaceholder")} disabled={!!editing} />
          </Form.Item>
          <Form.Item label={t("sysParams.paramValue")} name="paramValue" rules={[{ required: true, message: t("sysParams.paramValue") }]}>
            <Input.TextArea rows={4} placeholder={t("sysParamsExt.paramValuePlaceholder")} />
          </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((item) => ({ label: item.itemLabel, value: item.itemValue }))} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={t("common.status")} name="status" initialValue={1}>
                <Select options={statusDict.map((item) => ({ label: item.itemLabel, value: Number(item.itemValue) }))} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label={<Space>{t("sysParams.isSystem")}<Tooltip title={t("sysParamsExt.systemHint")}><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={t("sysParamsExt.descriptionPlaceholder")} />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}