import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
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';
import { DICT_TYPE, getDictLabel } from '../../utils/dict';

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

export default function MailTemplateManagement(props: MailTemplateManagementProps = {}) {
  const { t } = useTranslation();
  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 || t('mailTemplate.fetchListFailed'));
    } 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 getStatusLabel = (status: number | undefined) => {
    return status !== undefined && status !== null
      ? (getDictLabel(DICT_TYPE.COMMON_STATUS, status) || (status === 1 ? t('mailTemplate.enable') : t('mailTemplate.disable')))
      : '-';
  };
  const getStatusStyle = (status: number | undefined) => {
    const label = getStatusLabel(status);
    const isEnabled = label === '开启' || label === '启用' || label === '正常' || status === 1;
    return isEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700';
  };

  // 删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: t('notificationManagement.deleteEmailConfirmContent'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await emailTemplateApi.deleteMailTemplate(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 表格列配置
  const columns: ColumnsType<MailTemplateVO> = [
    {
      title: t('common.serialNumber'),
      width: 80,
      align: 'center',
      render: (_: any, __: MailTemplateVO, index: number) => {
        return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: t('mailTemplate.name'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('mailTemplate.code'),
      dataIndex: 'code',
      key: 'code',
      align: 'center',
    },
    {
      title: t('mailTemplate.title'),
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      render: (text: string) => text || '-',
    },
    {
      title: t('mailTemplate.status'),
      dataIndex: 'status',
      width: 100,
      align: 'center',
      render: (status: number | undefined) => (
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(status)}`}>
          {getStatusLabel(status)}
        </span>
      ),
    },
    {
      title: t('mailTemplate.remark'),
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      render: (text: string) => text || '-',
    },
    {
      title: t('common.operation'),
      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">{t('mailTemplate.test')}</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">{t('common.edit')}</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">{t('common.delete')}</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 justify-between gap-4 flex-wrap">
          {/* 搜索条件 + 搜索、重置紧跟其后 */}
          <div className="flex items-center gap-4 flex-wrap">
            <div className="flex items-center gap-2">
              <label className="text-sm text-gray-700 whitespace-nowrap">{t('mailTemplate.name')}：</label>
              <Input
                placeholder={t('mailTemplate.namePlaceholder')}
                value={queryParams.name}
                onChange={(e) => setQueryParams({ ...queryParams, name: e.target.value })}
                onPressEnter={handleQuery}
                className="w-[160px]"
                allowClear
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="text-sm text-gray-700 whitespace-nowrap">{t('mailTemplate.code')}：</label>
              <Input
                placeholder={t('mailTemplate.codePlaceholder')}
                value={queryParams.code}
                onChange={(e) => setQueryParams({ ...queryParams, code: e.target.value })}
                onPressEnter={handleQuery}
                className="w-[160px]"
                allowClear
              />
            </div>
            <Space size="small">
              <Button
                type="primary"
                icon={<Search className="w-4 h-4" />}
                onClick={handleQuery}
              >
                {t('common.search')}
              </Button>
              <Button icon={<RefreshCw className="w-4 h-4" />} onClick={resetQuery}>
                {t('common.reset')}
              </Button>
            </Space>
          </div>
          {/* 右侧按钮：新增、返回等保持不变 */}
          <div className="flex items-center gap-2 flex-shrink-0">
            <Button
              type="primary"
              icon={<Plus className="w-4 h-4" />}
              onClick={() => openForm('create')}
            >
              {t('common.addNew')}
            </Button>
            {onBack && (
              <Button
                icon={<ArrowLeft className="w-4 h-4" />}
                onClick={onBack}
              >
                {t('mailTemplate.backToEmailNotify')}
              </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">
                {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
              </div>
              <div className="flex items-center gap-2">
                <Button
                  size="small"
                  disabled={queryParams.pageNo === 1}
                  onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
                >
                  {t('common.prevPage')}
                </Button>
                <span className="text-sm text-gray-600">
                  {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize) || 1}
                </span>
                <Button
                  size="small"
                  disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize)}
                  onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
                >
                  {t('common.nextPage')}
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>

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

