import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, Plus, RefreshCw, Settings, ArrowLeft, Edit2, Trash2 } from 'lucide-react';
import { mailNotifyConfigApi, MailNotifyConfigVO } from '../../api/mailNotifyConfig';
import { toast } from 'sonner';
import { Modal, Table, Input, Button, Switch, Space } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from '../ui/button';
import type { ColumnsType } from 'antd/es/table';
import EmailNotifyForm, { EmailNotifyFormRef } from './EmailNotifyForm';
import MailTemplateManagement from '../mailTemplate/MailTemplateManagement';

export default function EmailNotifyManagement() {
  const { t } = useTranslation();
  console.log('EmailNotifyManagement 组件开始渲染');
  const [showTemplateManagement, setShowTemplateManagement] = useState(false);
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<MailNotifyConfigVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState({
    pageNo: 1,
    pageSize: 10,
    name: '',
    templateName: '',
  });

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

  // 获取列表（归一化主键：后端可能返回 id 或 configId，统一保证有 id 供编辑/删除使用，传递 id 时不能使用 configId）
  const getList = async (params?: typeof queryParams) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      const response = await mailNotifyConfigApi.listIsMailNotifyConfigPage(currentParams);
      const rawList = response.list || [];
      const listWithId = rawList.map((item: MailNotifyConfigVO) => ({
        ...item,
        id: (item as any).id ?? item.configId,
      }));
      setList(listWithId);
      setTotal(response.total || 0);
    } catch (error: any) {
      console.error('EmailNotifyManagement: 获取列表失败:', error);
      toast.error(error.message || t('notificationManagement.getEmailListFailed'));
    } 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: '',
      templateName: '',
    };
    setQueryParams(resetParams);
    getList(resetParams);
  };

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

  // 删除
  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 mailNotifyConfigApi.deleteIsMailNotifyConfig(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 状态修改
  const handleStatusChange = async (checked: boolean, record: MailNotifyConfigVO) => {
    try {
      const data: MailNotifyConfigVO = {
        ...record,
        status: checked ? '1' : '0',
      };
      await mailNotifyConfigApi.updateIsMailNotifyConfig(data);
      toast.success(checked ? t('notificationManagement.activateSuccess') : t('notificationManagement.deactivateSuccess'));
      await getList();
    } catch (error: any) {
      toast.error(error.message || t('notificationManagement.statusChangeFailed'));
      // 恢复原状态
      await getList();
    }
  };

  // 格式化时间
  const formattedTime = (totalSeconds?: number) => {
    if (!totalSeconds) return '-';
    const days = Math.floor(totalSeconds / (24 * 60 * 60));
    const hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60));
    const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
    const seconds = totalSeconds % 60;
    const parts = [];
    if (days > 0) parts.push(`${days}${t('common.day')}`);
    if (hours > 0) parts.push(`${hours}${t('common.hour')}`);
    if (minutes > 0) parts.push(`${minutes}${t('common.minute')}`);
    if (seconds > 0) parts.push(`${seconds}${t('common.second')}`);
    return parts.length > 0 ? parts.join(' ') : `0${t('common.second')}`;
  };

  // 表格列配置
  const columns: ColumnsType<MailNotifyConfigVO> = [
    {
      title: t('common.serialNumber'),
      key: 'index',
      width: 80,
      align: 'center',
      render: (_: any, __: MailNotifyConfigVO, index: number) => {
        return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: t('notificationManagement.reminderItem'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('notificationManagement.isActive'),
      key: 'status',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      render: (status: string | undefined, record: MailNotifyConfigVO) => {
        const isChecked = status === '1';
        return (
          <Switch
            checked={isChecked}
            checkedChildren="ON"
            unCheckedChildren="OFF"
            onChange={(checked) => handleStatusChange(checked, record)}
          />
        );
      },
    },
    {
      title: t('notificationManagement.templateCode'),
      dataIndex: 'templateCode',
      key: 'templateCode',
      align: 'center',
    },
    {
      title: t('notificationManagement.reminderDuration'),
      key: 'reminderTime',
      align: 'center',
      render: (_: any, record: MailNotifyConfigVO) => {
        return formattedTime(record.reminderTime);
      },
    },
    {
      title: t('common.operation'),
      key: 'action',
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: MailNotifyConfigVO) => {
        return (
          <div className="flex items-center gap-2 justify-center">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => openForm('update', (record as any).id ?? record.configId)}
              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={() => {
                const id = (record as any).id ?? record.configId;
                if (id != null) handleDelete(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>
        );
      },
    },
  ];

  // 如果显示邮件模板管理，直接返回模板管理组件（不显示邮件提醒的搜索栏）
  if (showTemplateManagement) {
    return <MailTemplateManagement onBack={() => setShowTemplateManagement(false)} />;
  }

  return (
    <div className="space-y-6">
      {/* 操作栏和表格容器 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
        {/* 查询与操作栏 */}
        <div className="p-4 lg:p-5 border-b border-gray-200/50">
          <div className="flex flex-wrap items-center justify-between gap-3">
            {/* 搜索条件 + 搜索、重置紧跟其后 */}
            <div className="flex flex-wrap items-center gap-3">
              {/* 提醒事项 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.reminderItem')}：</label>
                <Input
                  placeholder={t('notificationManagement.placeholderReminderItem')}
                  value={queryParams.name}
                  onChange={(e) => setQueryParams({ ...queryParams, name: e.target.value })}
                  onPressEnter={handleQuery}
                  allowClear
                  style={{ width: 200 }}
                />
              </div>

              {/* 邮件模板 */}
              {/* <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">邮件模板：</label>
                <Input
                  placeholder="请输入邮件模板"
                  value={queryParams.templateName}
                  onChange={(e) => setQueryParams({ ...queryParams, templateName: e.target.value })}
                  onPressEnter={handleQuery}
                  allowClear
                  style={{ width: 200 }}
                />
              </div> */}
              <Space size="small">
                <Button
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                  disabled={loading}
                >
                  {t('common.search')}
                </Button>
                <Button
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </Space>
            </div>

            {/* 其他操作按钮保持在右侧（新增、设置模板） */}
            <Space size="small">
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </Button>
              <Button
                icon={<Settings className="w-4 h-4" />}
                onClick={() => setShowTemplateManagement(true)}
              >
                {t('notificationManagement.setMailTemplate')}
              </Button>
            </Space>
          </div>
        </div>

        {/* 表格容器 */}
        <div className="overflow-hidden min-w-0">
          <Table
            columns={columns}
            dataSource={list}
            rowKey="id"
            loading={loading}
            pagination={false}
            scroll={{ x: 'max-content' }}
            locale={{
              emptyText: t('common.noData'),
            }}
          />
        </div>
      </div>

      {/* 分页 */}
      {!loading && total > 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 gap-2">
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
                disabled={queryParams.pageNo === 1 || loading}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
                disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize) || loading || Math.ceil(total / queryParams.pageSize) === 0}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 表单弹窗 */}
      <EmailNotifyForm ref={formRef} onSuccess={getList} />
    </div>
  );
}

