import React, { useState, useMemo, useRef, useEffect } 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 { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { useToast } from '@/components/ui/use-toast';
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 type {
  NotificationChannel,
  NotificationChannelQuery,
  ChannelTypeOption,
} from './types';
import { NotificationChannelType } from './types';
import {
  getChannelsPage,
  getChannelTypes,
  deleteChannel,
  enableChannel,
  disableChannel,
  testConnection,
} from './service';
import NotificationChannelDialog from './components/NotificationChannelDialog';

const NotificationChannelList: React.FC = () => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<NotificationChannel>>(null);

  // 状态管理
  const [channelTypes, setChannelTypes] = useState<ChannelTypeOption[]>([]);
  const [testing, setTesting] = useState<number | null>(null);
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });

  // 对话框状态
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editId, setEditId] = useState<number | undefined>();
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<number | null>(null);

  // 加载渠道类型
  useEffect(() => {
    loadChannelTypes();
  }, []);

  const loadChannelTypes = async () => {
    try {
      const types = await getChannelTypes();
      setChannelTypes(types);
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '加载渠道类型失败',
        description: error.response?.data?.message || error.message,
      });
    }
  };

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: any) => {
    const result = await getChannelsPage({
      ...query,
      page: query.pageNum,
      size: query.pageSize,
    });
    // 更新统计
    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 = () => {
    setEditId(undefined);
    setDialogOpen(true);
  };

  const handleEdit = (id: number) => {
    setEditId(id);
    setDialogOpen(true);
  };

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

  const handleDelete = async () => {
    if (!deleteId) return;
    await deleteChannel(deleteId);
  };

  // 启用/禁用
  const handleToggleStatus = async (id: number, enabled: boolean) => {
    try {
      if (enabled) {
        await enableChannel(id);
        toast({ title: '已启用' });
      } else {
        await disableChannel(id);
        toast({ title: '已禁用' });
      }
      tableRef.current?.refresh();
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '操作失败',
        description: error.response?.data?.message || error.message,
      });
    }
  };

  // 测试连接
  const handleTest = async (id: number) => {
    setTesting(id);
    try {
      const result = await testConnection(id);
      if (result) {
        toast({
          title: '测试成功',
          description: '渠道配置正确，连接正常',
        });
      } else {
        toast({
          variant: 'destructive',
          title: '测试失败',
          description: '渠道配置有误或连接异常',
        });
      }
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '测试失败',
        description: error.response?.data?.message || error.message,
      });
    } finally {
      setTesting(null);
    }
  };

  // 渠道类型标签
  const getChannelTypeBadge = (type: NotificationChannelType) => {
    const typeMap = {
      [NotificationChannelType.WEWORK]: {
        label: '企业微信',
        variant: 'default' as const,
      },
      [NotificationChannelType.EMAIL]: {
        label: '邮件',
        variant: 'secondary' as const,
      },
    };
    const config = typeMap[type];
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'name', type: 'input', placeholder: '搜索渠道名称', width: 'w-[200px]' },
    {
      key: 'channelType',
      type: 'select',
      placeholder: '渠道类型',
      width: 'w-[150px]',
      options: channelTypes
        .filter((type) => type.code && type.code.trim() !== '')
        .map((type) => ({ label: type.label, value: type.code })),
    },
  ], [channelTypes]);

  // 列定义
  const columns: ColumnDef<NotificationChannel>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'name', title: '渠道名称', dataIndex: 'name', width: '150px' },
    {
      key: 'channelType',
      title: '渠道类型',
      width: '120px',
      render: (_, record) => getChannelTypeBadge(record.channelType),
    },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, record) => (
        <Badge variant={record.enabled ? 'default' : 'secondary'}>
          {record.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    { 
      key: 'description', 
      title: '描述', 
      width: '200px',
      render: (_, record) => (
        <div className="truncate max-w-[200px]" title={record.description || ''}>
          {record.description || '-'}
        </div>
      ),
    },
    { 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={() => handleTest(record.id!)}
            disabled={testing === record.id}
            title="测试连接"
          >
            {testing === record.id ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <TestTube className="h-4 w-4" />
            )}
          </Button>
          {record.enabled ? (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => handleToggleStatus(record.id!, false)}
              title="禁用"
            >
              <PowerOff className="h-4 w-4" />
            </Button>
          ) : (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => handleToggleStatus(record.id!, true)}
              title="启用"
            >
              <Power className="h-4 w-4" />
            </Button>
          )}
          <Button
            size="sm"
            variant="ghost"
            onClick={() => handleEdit(record.id!)}
            title="编辑"
          >
            <Edit className="h-4 w-4" />
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => {
              setDeleteId(record.id!);
              setDeleteDialogOpen(true);
            }}
            className="text-destructive hover:text-destructive"
            title="删除"
          >
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      ),
    },
  ], [testing, channelTypes]);

  // 工具栏
  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">
              管理通知渠道配置，支持企业微信、邮件等多种渠道
            </CardDescription>
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<NotificationChannel, any>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1200px"
          />
        </CardContent>
      </Card>

      {/* 创建/编辑对话框 */}
      <NotificationChannelDialog
        open={dialogOpen}
        editId={editId}
        channelTypes={channelTypes}
        onOpenChange={setDialogOpen}
        onSuccess={handleSuccess}
      />

      {/* 删除确认对话框 */}
      <ConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        title="确认删除"
        description="确定要删除这个通知渠道吗？此操作不可撤销。"
        item={deleteId}
        onConfirm={handleDelete}
        onSuccess={() => {
          toast({ title: '删除成功' });
          setDeleteId(null);
          tableRef.current?.refresh();
        }}
        onCancel={() => setDeleteId(null)}
        variant="destructive"
        confirmText="删除"
      />
    </PageContainer>
  );
};

export default NotificationChannelList;

