import React, { useState, useMemo, useRef } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/components/ui/use-toast';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { Plus, Edit, Trash2, Link, Server, Activity, Database } from 'lucide-react';
import EditDialog from './components/EditDialog';
import DeleteDialog from './components/DeleteDialog';
import * as service from './service';
import type { ExternalSystemResponse, ExternalSystemQuery, SystemType, AuthType } from './types';

const DEFAULT_PAGE_SIZE = 10;

const ExternalPage: React.FC = () => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<ExternalSystemResponse>>(null);
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });

  // 对话框状态
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ExternalSystemResponse>();

  // 包装 fetchFn
  const fetchData = async (query: ExternalSystemQuery) => {
    const response = await service.getExternalSystemsPage(query);
    // 计算统计数据
    const all = response.content || [];
    setStats({
      total: response.totalElements || 0,
      enabled: all.filter((item) => item.enabled).length,
      disabled: all.filter((item) => !item.enabled).length,
    });
    return response;
  };

  const handleSuccess = () => {
    tableRef.current?.refresh();
  };

  // 测试连接
  const handleTestConnection = async (id: number) => {
    try {
      const success = await service.testConnection(id);
      toast({
        title: success ? '连接成功' : '连接失败',
        description: success ? '外部系统连接正常' : '无法连接到外部系统',
        variant: success ? 'default' : 'destructive',
      });
      // 刷新列表以更新最后连接时间等信息
      tableRef.current?.refresh();
    } catch (error) {
      toast({ title: '测试失败', description: '无法测试连接', variant: 'destructive' });
    }
  };

  // 切换状态
  const handleStatusChange = async (id: number, enabled: boolean) => {
    try {
      await service.updateStatus(id, enabled);
      toast({ title: '更新成功', description: `系统状态已${enabled ? '启用' : '禁用'}` });
      tableRef.current?.refresh();
    } catch (error) {
      toast({ title: '更新失败', description: '无法更新系统状态', variant: 'destructive' });
    }
  };

  // 获取系统类型标签
  const getSystemTypeLabel = (type: SystemType) => {
    const typeMap = {
      JENKINS: { label: 'Jenkins', variant: 'default' as const },
      GIT: { label: 'Git', variant: 'secondary' as const },
      ZENTAO: { label: '禅道', variant: 'outline' as const },
    };
    return typeMap[type] || { label: type, variant: 'outline' as const };
  };

  // 获取认证方式标签
  const getAuthTypeLabel = (authType: AuthType) => {
    const authTypeMap = {
      BASIC: '用户名密码',
      TOKEN: '令牌',
      OAUTH: 'OAuth2',
    };
    return authTypeMap[authType];
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'name', type: 'input', placeholder: '系统名称', width: 'w-[200px]' },
    {
      key: 'type',
      type: 'select',
      placeholder: '系统类型',
      width: 'w-[200px]',
      options: [
        { label: 'Jenkins', value: 'JENKINS' },
        { label: 'Git', value: 'GIT' },
        { label: '禅道', value: 'ZENTAO' },
      ],
    },
    {
      key: 'enabled',
      type: 'select',
      placeholder: '状态',
      width: 'w-[200px]',
      options: [
        { label: '已启用', value: 'true' },
        { label: '已禁用', value: 'false' },
      ],
    },
  ], []);

  // 列定义
  const columns: ColumnDef<ExternalSystemResponse>[] = useMemo(() => [
    {
      key: 'id',
      title: 'ID',
      dataIndex: 'id',
      width: '80px',
    },
    {
      key: 'name',
      title: '系统名称',
      dataIndex: 'name',
      width: '150px',
    },
    {
      key: 'type',
      title: '系统类型',
      width: '100px',
      render: (_, item) => {
        const typeInfo = getSystemTypeLabel(item.type);
        return <Badge variant={typeInfo.variant}>{typeInfo.label}</Badge>;
      },
    },
    {
      key: 'url',
      title: '系统地址',
      width: '250px',
      render: (_, item) => (
        <a
          href={item.url}
          target="_blank"
          rel="noopener noreferrer"
          className="text-blue-600 hover:underline flex items-center gap-1"
          onClick={() => {
            setTimeout(() => tableRef.current?.refresh(), 100);
          }}
        >
          <Link className="h-3 w-3" />
          {item.url}
        </a>
      ),
    },
    {
      key: 'authType',
      title: '认证方式',
      width: '120px',
      render: (_, item) => getAuthTypeLabel(item.authType),
    },
    {
      key: 'lastConnectTime',
      title: '最后连接时间',
      dataIndex: 'lastConnectTime',
      width: '150px',
      render: (value) => value || '-',
    },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, item) => (
        <Switch
          checked={item.enabled}
          onCheckedChange={(checked) => handleStatusChange(item.id, checked)}
        />
      ),
    },
    {
      key: 'actions',
      title: '操作',
      width: '250px',
      sticky: true,
      render: (_, item) => (
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="sm"
            className="h-8 px-2"
            onClick={() => {
              setCurrentRecord(item);
              setEditDialogOpen(true);
            }}
          >
            <Edit className="h-3.5 w-3.5 mr-1" />
            编辑
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 px-2"
            onClick={() => handleTestConnection(item.id)}
          >
            <Link className="h-3.5 w-3.5 mr-1" />
            测试连接
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 px-2 text-destructive hover:text-destructive"
            onClick={() => {
              setCurrentRecord(item);
              setDeleteDialogOpen(true);
            }}
          >
            <Trash2 className="h-3.5 w-3.5 mr-1" />
            删除
          </Button>
        </div>
      ),
    },
  ], []);

  return (
    <PageContainer>
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">外部服务管理</h2>
        <Button onClick={() => {
          setCurrentRecord(undefined);
          setEditDialogOpen(true);
        }}>
          <Plus className="h-4 w-4 mr-2" />
          新增系统
        </Button>
      </div>

      {/* 统计卡片 */}
      <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>
          <CardTitle>系统列表</CardTitle>
        </CardHeader>
        <CardContent>
          <PaginatedTable<ExternalSystemResponse, ExternalSystemQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            rowKey="id"
            minWidth="1120px"
            pageSize={DEFAULT_PAGE_SIZE}
          />
        </CardContent>
      </Card>

      {/* 对话框 */}
      <EditDialog
        open={editDialogOpen}
        record={currentRecord}
        onOpenChange={setEditDialogOpen}
        onSuccess={handleSuccess}
      />
      <DeleteDialog
        open={deleteDialogOpen}
        record={currentRecord}
        onOpenChange={setDeleteDialogOpen}
        onSuccess={handleSuccess}
      />
    </PageContainer>
  );
};

export default ExternalPage;
