import React, { useState, useEffect } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/components/ui/use-toast';
import { DataTablePagination } from '@/components/ui/pagination';
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 [list, setList] = useState<ExternalSystemResponse[]>([]);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState<ExternalSystemQuery>({
    pageNum: 1,
    pageSize: DEFAULT_PAGE_SIZE,
  });
  const [total, setTotal] = useState(0);
  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>();

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await service.getExternalSystemsPage(query);
      if (response) {
        setList(response.content || []);
        setTotal(response.totalElements || 0);
        // 计算统计数据
        const all = response.content || [];
        setStats({
          total: all.length,
          enabled: all.filter((item) => item.enabled).length,
          disabled: all.filter((item) => !item.enabled).length,
        });
      }
    } catch (error) {
      toast({ title: '加载失败', description: '无法加载外部系统列表', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [query.pageNum, query.pageSize]);

  // 搜索
  const handleSearch = () => {
    setQuery({ ...query, pageNum: 1 });
    loadData();
  };

  // 重置
  const handleReset = () => {
    setQuery({ pageNum: 1, pageSize: DEFAULT_PAGE_SIZE });
    loadData();
  };

  // 测试连接
  const handleTestConnection = async (id: number) => {
    try {
      const success = await service.testConnection(id);
      toast({
        title: success ? '连接成功' : '连接失败',
        description: success ? '外部系统连接正常' : '无法连接到外部系统',
        variant: success ? 'default' : 'destructive',
      });
    } catch (error) {
      toast({ title: '测试失败', description: '无法测试连接', variant: 'destructive' });
    }
  };

  // 切换状态
  const handleStatusChange = async (id: number, enabled: boolean) => {
    try {
      await service.updateStatus(id, enabled);
      toast({ title: '更新成功', description: `系统状态已${enabled ? '启用' : '禁用'}` });
      loadData();
    } 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];
  };

  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>
        <div className="p-6">
          <div className="flex items-center gap-4">
            <Input
              placeholder="系统名称"
              value={query.name || ''}
              onChange={(e) => setQuery({ ...query, name: e.target.value })}
              className="max-w-[200px]"
            />
            <Select
              value={query.type}
              onValueChange={(value) => setQuery({ ...query, type: value as SystemType })}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="系统类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="JENKINS">Jenkins</SelectItem>
                <SelectItem value="GIT">Git</SelectItem>
                <SelectItem value="ZENTAO">禅道</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={query.enabled?.toString()}
              onValueChange={(value) => setQuery({ ...query, enabled: value === 'true' })}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="true">已启用</SelectItem>
                <SelectItem value="false">已禁用</SelectItem>
              </SelectContent>
            </Select>
            <Button variant="outline" onClick={handleReset}>
              重置
            </Button>
            <Button onClick={handleSearch}>
              搜索
            </Button>
          </div>
        </div>
      </Card>

      {/* 数据表格 */}
      <Card>
        <CardHeader>
          <CardTitle>系统列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[150px]">系统名称</TableHead>
                  <TableHead className="w-[100px]">系统类型</TableHead>
                  <TableHead className="w-[250px]">系统地址</TableHead>
                  <TableHead className="w-[120px]">认证方式</TableHead>
                  <TableHead className="w-[150px]">最后连接时间</TableHead>
                  <TableHead className="w-[100px]">状态</TableHead>
                  <TableHead className="w-[250px]">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {list.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="h-24 text-center">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  list.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">{item.name}</TableCell>
                      <TableCell>
                        <Badge variant={getSystemTypeLabel(item.type).variant}>
                          {getSystemTypeLabel(item.type).label}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <a
                          href={item.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:underline flex items-center gap-1"
                        >
                          <Link className="h-3 w-3" />
                          {item.url}
                        </a>
                      </TableCell>
                      <TableCell>{getAuthTypeLabel(item.authType)}</TableCell>
                      <TableCell className="text-muted-foreground">
                        {item.lastConnectTime || '-'}
                      </TableCell>
                      <TableCell>
                        <Switch
                          checked={item.enabled}
                          onCheckedChange={(checked) => handleStatusChange(item.id, checked)}
                        />
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setCurrentRecord(item);
                              setEditDialogOpen(true);
                            }}
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            编辑
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleTestConnection(item.id)}
                          >
                            <Link className="h-4 w-4 mr-1" />
                            测试连接
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setCurrentRecord(item);
                              setDeleteDialogOpen(true);
                            }}
                            className="text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-4 w-4 mr-1" />
                            删除
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
            <div className="flex justify-end border-t border-border bg-muted/40">
              <DataTablePagination
                pageIndex={query.pageNum || 1}
                pageSize={query.pageSize || DEFAULT_PAGE_SIZE}
                pageCount={Math.ceil(total / (query.pageSize || DEFAULT_PAGE_SIZE))}
                onPageChange={(page) => setQuery({ ...query, pageNum: page })}
              />
            </div>
          </div>
        </CardContent>
      </Card>

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

export default ExternalPage;
