import React, { useState, useEffect, useMemo, useRef } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import { getTeams } from './service';
import type { TeamResponse, TeamQuery } from './types';
import { DEVELOPMENT_MODE_OPTIONS } from './types';
import TeamModal from './components/TeamModal';
import DeleteDialog from './components/DeleteDialog';
import MemberManageDialog from './components/MemberManageDialog';
import { getUserList } from '@/pages/System/User/List/service';
import type { UserResponse } from '@/pages/System/User/List/types';
import { getEnvironmentList } from './service';
import type { Environment } from './types';
import { TeamEnvironmentManageDialog } from './components/TeamEnvironmentManageDialog';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Plus,
  Edit,
  Trash2,
  Users,
  Activity,
  Server,
  Database,
  MoreHorizontal,
  Settings,
} from 'lucide-react';

const TeamList: React.FC = () => {
  const tableRef = useRef<PaginatedTableRef<TeamResponse>>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentTeam, setCurrentTeam] = useState<TeamResponse | undefined>();
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [memberDialogOpen, setMemberDialogOpen] = useState(false);
  const [envManageDialogOpen, setEnvManageDialogOpen] = useState(false);
  const [users, setUsers] = useState<UserResponse[]>([]);
  const [environments, setEnvironments] = useState<Environment[]>([]);
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });

  // 加载基础数据（仅一次）
  useEffect(() => {
    loadUsers();
    loadEnvironments();
  }, []);

  const loadUsers = async () => {
    try {
      const response = await getUserList();
      if (response) {
        setUsers(response);
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
    }
  };

  const loadEnvironments = async () => {
    try {
      const response = await getEnvironmentList();
      if (response) {
        setEnvironments(response);
      }
    } catch (error) {
      console.error('加载环境列表失败:', error);
    }
  };

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: TeamQuery) => {
    const result = await getTeams(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 handleSuccess = () => {
    tableRef.current?.refresh();
  };

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

  const handleEdit = (record: TeamResponse) => {
    setCurrentTeam(record);
    setModalVisible(true);
  };

  const handleDelete = (record: TeamResponse) => {
    setCurrentTeam(record);
    setDeleteDialogOpen(true);
  };

  const handleManageMembers = (record: TeamResponse) => {
    setCurrentTeam(record);
    setMemberDialogOpen(true);
  };

  const handleManageEnvironments = (record: TeamResponse) => {
    setCurrentTeam(record);
    setEnvManageDialogOpen(true);
  };

  const handleModalOpenChange = (open: boolean) => {
    setModalVisible(open);
    if (!open) {
      setCurrentTeam(undefined);
    }
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'teamCode', type: 'input', placeholder: '团队编码', width: 'w-[180px]' },
    { key: 'teamName', type: 'input', placeholder: '团队名称', width: 'w-[180px]' },
    {
      key: 'enabled',
      type: 'select',
      placeholder: '状态',
      width: 'w-[120px]',
      options: [
        { label: '启用', value: 'true' },
        { label: '禁用', value: 'false' },
      ],
    },
  ], []);

  // 列定义
  const columns: ColumnDef<TeamResponse>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'teamCode', title: '团队编码', dataIndex: 'teamCode', width: '180px' },
    { key: 'teamName', title: '团队名称', dataIndex: 'teamName', width: '180px' },
    { key: 'description', title: '团队描述', dataIndex: 'description', width: '260px' },
    {
      key: 'ownerName',
      title: '负责人',
      width: '140px',
      render: (_, record) => record.ownerName || '-',
    },
    {
      key: 'developmentMode',
      title: '开发模式',
      width: '120px',
      render: (_, record) => {
        const modeOption = DEVELOPMENT_MODE_OPTIONS.find(opt => opt.value === record.developmentMode);
        
        // 根据不同模式设置颜色
        const getBadgeVariant = (mode: string) => {
          switch (mode) {
            case 'STANDARD': return 'outline' as const;
            case 'SYNC_MODE': return 'default' as const;  // 蓝色
            case 'ARTIFACT_DELIVERY': return 'secondary' as const;  // 灰色
            default: return 'outline' as const;
          }
        };
        
        return (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Badge 
                  variant={getBadgeVariant(record.developmentMode)} 
                  className="cursor-help inline-flex items-center gap-1"
                >
                  {modeOption?.label || record.developmentMode}
                  {record.enableGitSyncCheck && (
                    <span className="text-xs">🔄</span>
                  )}
                </Badge>
              </TooltipTrigger>
              <TooltipContent side="right" className="max-w-xs">
                <div className="space-y-1 text-xs">
                  <div className="font-semibold">{modeOption?.label}</div>
                  <div className="text-muted-foreground">{modeOption?.description}</div>
                  {record.enableGitSyncCheck && (
                    <div className="text-blue-600 border-t pt-1 mt-1">
                      ✓ 已启用Git同步检测
                    </div>
                  )}
                </div>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        );
      },
    },
    {
      key: 'memberCount',
      title: '成员数量',
      width: '100px',
      render: (_, record) => (
        <div className="text-center">
          <span className="font-medium">{record.memberCount || 0}</span>
        </div>
      ),
    },
    {
      key: 'environmentCount',
      title: '环境数量',
      width: '100px',
      render: (_, record) => (
        <div className="text-center">
          <Badge variant="outline" className="font-medium">
            {record.environmentCount || 0}
          </Badge>
        </div>
      ),
    },
    {
      key: 'applicationCount',
      title: '应用数量',
      width: '100px',
      render: (_, record) => (
        <div className="text-center">
          <Badge variant="outline" className="font-medium">
            {record.applicationCount || 0}
          </Badge>
        </div>
      ),
    },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, record) => (
        <Badge variant={record.enabled ? 'default' : 'secondary'} className="inline-flex">
          {record.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    { key: 'sort', title: '排序', dataIndex: 'sort', width: '100px' },
    {
      key: 'actions',
      title: '操作',
      width: '120px',
      sticky: true,
      render: (_, record) => (
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="sm">
                <MoreHorizontal className="h-4 w-4" />
                操作
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => handleManageEnvironments(record)}>
                <Settings className="mr-2 h-4 w-4" />
                环境管理
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => handleManageMembers(record)}>
                <Users className="mr-2 h-4 w-4" />
                管理成员
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => handleEdit(record)}>
                <Edit className="mr-2 h-4 w-4" />
                编辑团队
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => handleDelete(record)}
                className="text-destructive focus:text-destructive"
              >
                <Trash2 className="mr-2 h-4 w-4" />
                删除团队
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      ),
    },
  ], []);

  // 工具栏
  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<TeamResponse, TeamQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1440px"
          />
        </CardContent>
      </Card>

      {/* 对话框 */}
      <TeamModal
        open={modalVisible}
        onOpenChange={handleModalOpenChange}
        onSuccess={handleSuccess}
        initialValues={currentTeam}
      />
      <DeleteDialog
        open={deleteDialogOpen}
        record={currentTeam}
        onOpenChange={setDeleteDialogOpen}
        onSuccess={handleSuccess}
      />
      {currentTeam && (
        <>
          <MemberManageDialog
            open={memberDialogOpen}
            teamId={currentTeam.id}
            teamName={currentTeam.teamName}
            ownerId={currentTeam.ownerId}
            users={users}
            onOpenChange={setMemberDialogOpen}
            onSuccess={handleSuccess}
          />
          <TeamEnvironmentManageDialog
            open={envManageDialogOpen}
            onOpenChange={setEnvManageDialogOpen}
            teamId={currentTeam.id}
            teamName={currentTeam.teamName}
            enableGitSyncCheck={currentTeam.enableGitSyncCheck}
            environments={environments}
            users={users}
            onSuccess={handleSuccess}
          />
        </>
      )}
    </PageContainer>
  );
};

export default TeamList;
