/**
 * 通知模板管理页面
 */
import React, { useState, useMemo, useRef } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { useToast } from '@/components/ui/use-toast';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import {
  Plus,
  Edit,
  Trash2,
  TestTube,
  Power,
  PowerOff,
  Activity,
  Database,
  Server,
  Loader2,
} from 'lucide-react';
import { NotificationChannelType } from '../../NotificationChannel/List/types';
import type { 
  NotificationTemplateDTO, 
  NotificationTemplateQuery,
  ChannelTypeOption 
} from './types';
import {
  getTemplateList,
  deleteTemplate,
  enableTemplate,
  disableTemplate,
} from './service';
import { NotificationTemplateDialog, TestTemplateDialog } from './components';

// 渠道类型选项
const CHANNEL_TYPE_OPTIONS: ChannelTypeOption[] = [
  {
    code: NotificationChannelType.WEWORK,
    label: '企业微信',
    description: '企业微信机器人通知',
  },
  {
    code: NotificationChannelType.EMAIL,
    label: '邮件',
    description: '邮件通知',
  },
];

const NotificationTemplateList: React.FC = () => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<NotificationTemplateDTO>>(null);
  
  // 状态管理
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });
  const [operationLoading, setOperationLoading] = useState({
    toggling: null as number | null,
  });
  
  // 对话框状态
  const [modalVisible, setModalVisible] = useState(false);
  const [currentTemplate, setCurrentTemplate] = useState<NotificationTemplateDTO | undefined>();
  const [testModalVisible, setTestModalVisible] = useState(false);
  const [testTemplate, setTestTemplate] = useState<NotificationTemplateDTO | undefined>();
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    title: string;
    description: string;
    onConfirm: () => Promise<void>;
  }>({
    open: false,
    title: '',
    description: '',
    onConfirm: async () => {},
  });

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: NotificationTemplateQuery) => {
    const result = await getTemplateList(query);
    // 更新统计
    const all = result.content || [];
    setStats({
      total: result.totalElements || 0,
      enabled: all.filter((item) => item.enabled).length,
      disabled: all.filter((item) => !item.enabled).length,
    });
    return result;
  };

  const handleAdd = () => {
    setCurrentTemplate(undefined);
    setModalVisible(true);
  };

  const handleEdit = (template: NotificationTemplateDTO) => {
    setCurrentTemplate(template);
    setModalVisible(true);
  };

  const handleSuccess = () => {
    setModalVisible(false);
    setCurrentTemplate(undefined);
    tableRef.current?.refresh();
  };

  // 删除模板
  const handleDelete = (template: NotificationTemplateDTO) => {
    setConfirmDialog({
      open: true,
      title: '删除模板',
      description: `确定要删除模板 "${template.name}" 吗？此操作不可恢复。`,
      onConfirm: async () => {
        try {
          await deleteTemplate(template.id);
          toast({ title: '删除成功' });
          tableRef.current?.refresh();
        } catch (error: any) {
          toast({
            variant: 'destructive',
            title: '删除失败',
            description: error.response?.data?.message || error.message,
          });
        }
        setConfirmDialog(prev => ({ ...prev, open: false }));
      },
    });
  };

  // 测试模板
  const handleTestTemplate = (template: NotificationTemplateDTO) => {
    setTestTemplate(template);
    setTestModalVisible(true);
  };

  // 启用/禁用模板
  const handleToggleStatus = async (template: NotificationTemplateDTO) => {
    setOperationLoading(prev => ({ ...prev, toggling: template.id }));
    try {
      if (template.enabled) {
        await disableTemplate(template.id);
        toast({ title: '已禁用' });
      } else {
        await enableTemplate(template.id);
        toast({ title: '已启用' });
      }
      tableRef.current?.refresh();
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '操作失败',
        description: error.response?.data?.message || error.message,
      });
    } finally {
      setOperationLoading(prev => ({ ...prev, toggling: null }));
    }
  };

  // 获取渠道类型标签
  const getChannelTypeLabel = (type: NotificationChannelType) => {
    const option = CHANNEL_TYPE_OPTIONS.find(opt => opt.code === type);
    return option?.label || type;
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'name', type: 'input', placeholder: '搜索模板名称或编码', width: 'w-[220px]' },
    {
      key: 'channelType',
      type: 'select',
      placeholder: '渠道类型',
      width: 'w-[150px]',
      options: CHANNEL_TYPE_OPTIONS.map((option) => ({
        label: option.label,
        value: option.code,
      })),
    },
  ], []);

  // 列定义
  const columns: ColumnDef<NotificationTemplateDTO>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'name', title: '模板名称', dataIndex: 'name', width: '150px' },
    { key: 'code', title: '模板编码', dataIndex: 'code', width: '150px' },
    { 
      key: 'titleTemplate', 
      title: '标题模板', 
      width: '200px',
      render: (_, record) => (
        <div className="truncate max-w-[200px]" title={record.titleTemplate || ''}>
          {record.titleTemplate || '-'}
        </div>
      ),
    },
    {
      key: 'channelType',
      title: '渠道类型',
      width: '120px',
      render: (_, record) => (
        <Badge variant="outline">{getChannelTypeLabel(record.channelType)}</Badge>
      ),
    },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, record) => (
        <Badge variant={record.enabled ? 'default' : 'secondary'}>
          {record.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    { key: 'createTime', title: '创建时间', dataIndex: 'createTime', width: '180px' },
    {
      key: 'actions',
      title: '操作',
      width: '240px',
      sticky: true,
      render: (_, record) => (
        <div className="flex items-center gap-2">
          <Button
            size="sm"
            variant="ghost"
            onClick={() => handleTestTemplate(record)}
            disabled={!record.enabled}
            title="测试模板"
          >
            <TestTube className="h-4 w-4" />
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => handleEdit(record)}
            disabled={operationLoading.toggling === record.id}
            title="编辑"
          >
            <Edit className="h-4 w-4" />
          </Button>
          {record.enabled ? (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => handleToggleStatus(record)}
              disabled={operationLoading.toggling === record.id}
              title="禁用"
            >
              {operationLoading.toggling === record.id ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <PowerOff className="h-4 w-4" />
              )}
            </Button>
          ) : (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => handleToggleStatus(record)}
              disabled={operationLoading.toggling === record.id}
              title="启用"
            >
              {operationLoading.toggling === record.id ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Power className="h-4 w-4" />
              )}
            </Button>
          )}
          <Button
            size="sm"
            variant="ghost"
            onClick={() => handleDelete(record)}
            disabled={operationLoading.toggling === record.id}
            className="text-destructive hover:text-destructive"
            title="删除"
          >
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      ),
    },
  ], [operationLoading.toggling]);

  // 工具栏
  const toolbar = (
    <Button onClick={handleAdd}>
      <Plus className="h-4 w-4 mr-2" />
      新建模板
    </Button>
  );

  return (
    <PageContainer>
      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总模板数</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">所有模板</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已启用</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.enabled}</div>
            <p className="text-xs text-muted-foreground">正在使用中</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已禁用</CardTitle>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-gray-600">{stats.disabled}</div>
            <p className="text-xs text-muted-foreground">暂时停用</p>
          </CardContent>
        </Card>
      </div>

      {/* 模板管理 */}
      <Card>
        <CardHeader>
          <div>
            <CardTitle>通知模板</CardTitle>
            <CardDescription className="mt-2">
              管理通知消息模板，支持 FreeMarker 语法
            </CardDescription>
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<NotificationTemplateDTO, NotificationTemplateQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1300px"
          />
        </CardContent>
      </Card>

      {/* 对话框 */}
      <NotificationTemplateDialog
        open={modalVisible}
        editId={currentTemplate?.id}
        channelTypes={CHANNEL_TYPE_OPTIONS}
        onOpenChange={setModalVisible}
        onSuccess={handleSuccess}
      />

      {/* 测试模板对话框 */}
      <TestTemplateDialog
        open={testModalVisible}
        template={testTemplate}
        onOpenChange={setTestModalVisible}
      />

      {/* 确认对话框 */}
      <ConfirmDialog
        open={confirmDialog.open}
        title={confirmDialog.title}
        description={confirmDialog.description}
        onConfirm={confirmDialog.onConfirm}
        onOpenChange={(open) => setConfirmDialog(prev => ({ ...prev, open }))}
      />
    </PageContainer>
  );
};

export default NotificationTemplateList;
