import React, { useState, useEffect, useRef } from 'react';
import { Search, Plus, RefreshCw, ArrowLeft, Edit2, Trash2 } from 'lucide-react';
import { emailTemplateApi, MailTemplateVO } from '../../api/emailTemplate';
import { toast } from 'sonner';
import { Modal, Table, Input, Button, Space, Switch } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from '../ui/button';
import type { ColumnsType } from 'antd/es/table';
import MailTemplateForm, { MailTemplateFormRef } from './MailTemplateForm';
import MailTemplateSendForm, { MailTemplateSendFormRef } from './MailTemplateSendForm';

interface MailTemplateManagementProps {
  onBack?: () => void;
}

export default function MailTemplateManagement(props: MailTemplateManagementProps = {}) {
  const { onBack } = props;
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<MailTemplateVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState({
    pageNo: 1,
    pageSize: 10,
    name: '',
    code: '',
    status: undefined as number | undefined,
  });

  // 子组件引用
  const formRef = useRef<MailTemplateFormRef>(null);
  const sendFormRef = useRef<MailTemplateSendFormRef>(null);

  // 获取列表
  const getList = async (params?: typeof queryParams) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      const response = await emailTemplateApi.getMailTemplatePage(currentParams);
      setList(response.list || []);
      setTotal(response.total || 0);
    } catch (error: any) {
      toast.error(error.message || '获取邮件模板列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.pageNo, queryParams.pageSize]);

  // 搜索
  const handleQuery = () => {
    const newParams = { ...queryParams, pageNo: 1 };
    setQueryParams(newParams);
    getList(newParams);
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams = {
      pageNo: 1,
      pageSize: 10,
      name: '',
      code: '',
      status: undefined,
    };
    setQueryParams(resetParams);
    getList(resetParams);
  };

  // 打开表单弹窗
  const openForm = (type: string, id?: number) => {
    formRef.current?.open(type, id);
  };

  // 打开发送测试弹窗
  const openSendForm = (id: number) => {
    sendFormRef.current?.open(id);
  };

  // 删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这条邮件模板吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await emailTemplateApi.deleteMailTemplate(id);
          toast.success('删除成功');
          await getList();
        } catch (error: any) {
          toast.error(error.message || '删除失败');
        }
      },
    });
  };

  // 表格列配置
  const columns: ColumnsType<MailTemplateVO> = [
    {
      title: '序号',
      width: 80,
      align: 'center',
      render: (_: any, __: MailTemplateVO, index: number) => {
        return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: '模板名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '模板编码',
      dataIndex: 'code',
      key: 'code',
      align: 'center',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      render: (text: string) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      align: 'center',
      render: (status: number | undefined) => {
        return status === 1 ? '启用' : '禁用';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      render: (text: string) => text || '-',
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: MailTemplateVO) => {
        return (
          <div className="flex items-center gap-2 justify-center">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => openSendForm(record.id!)}
              className="h-8 px-2 transition-colors hover:text-[#1677ff] hover:underline"
            >
              <Search className="w-4 h-4" />
              <span className="ml-1">测试</span>
            </UIButton>
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => openForm('update', record.id)}
              className="h-8 px-2 transition-colors hover:text-[#1677ff] hover:underline"
            >
              <Edit2 className="w-4 h-4" />
              <span className="ml-1">编辑</span>
            </UIButton>
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => handleDelete(record.id!)}
              className="h-8 px-2 text-red-600 hover:text-[#1677ff] transition-colors hover:underline"
            >
              <Trash2 className="w-4 h-4" />
              <span className="ml-1">删除</span>
            </UIButton>
          </div>
        );
      },
    },
  ];

  return (
    <div className="space-y-6">
      {/* 搜索栏 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm p-6">
        <div className="flex items-center gap-4 flex-wrap">
          <div className="flex items-center gap-2 flex-1 min-w-[200px]">
            <label className="text-sm text-gray-700 whitespace-nowrap">模板名称：</label>
            <Input
              placeholder="请输入模板名称"
              value={queryParams.name}
              onChange={(e) => setQueryParams({ ...queryParams, name: e.target.value })}
              onPressEnter={handleQuery}
              className="flex-1 max-w-[240px]"
              allowClear
            />
          </div>
          <div className="flex items-center gap-2 flex-1 min-w-[200px]">
            <label className="text-sm text-gray-700 whitespace-nowrap">模板编码：</label>
            <Input
              placeholder="请输入模板编码"
              value={queryParams.code}
              onChange={(e) => setQueryParams({ ...queryParams, code: e.target.value })}
              onPressEnter={handleQuery}
              className="flex-1 max-w-[240px]"
              allowClear
            />
          </div>
          <div className="flex items-center gap-2">
            <Button
              type="primary"
              icon={<Search className="w-4 h-4" />}
              onClick={handleQuery}
            >
              搜索
            </Button>
            <Button icon={<RefreshCw className="w-4 h-4" />} onClick={resetQuery}>
              重置
            </Button>
            <Button
              type="primary"
              icon={<Plus className="w-4 h-4" />}
              onClick={() => openForm('create')}
            >
              新增
            </Button>
            {onBack && (
              <Button
                icon={<ArrowLeft className="w-4 h-4" />}
                onClick={onBack}
              >
                返回邮件提醒
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
        <Table
          columns={columns}
          dataSource={list}
          rowKey="id"
          loading={loading}
          pagination={false}
          scroll={{ x: 'max-content' }}
        />
        {/* 分页 */}
        {!loading && list.length > 0 && (
          <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
            <div className="flex items-center justify-between">
              <div className="text-sm text-gray-600">
                共 <span className="text-blue-600 font-medium">{total}</span> 条记录
              </div>
              <div className="flex items-center gap-2">
                <Button
                  size="small"
                  disabled={queryParams.pageNo === 1}
                  onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
                >
                  上一页
                </Button>
                <span className="text-sm text-gray-600">
                  第 {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize)} 页
                </span>
                <Button
                  size="small"
                  disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize)}
                  onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
                >
                  下一页
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 表单弹窗 */}
      <MailTemplateForm ref={formRef} onSuccess={getList} />
      {/* 发送测试弹窗 */}
      <MailTemplateSendForm ref={sendFormRef} />
    </div>
  );
}

