import React, { useState, useMemo } from 'react';
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Package, Shield, CheckCircle2, Search, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ApplicationCard } from './ApplicationCard';
import type { DeployTeam, DeployEnvironment, ApplicationConfig } from '../types';

interface EnvironmentTabsProps {
  team: DeployTeam;
  currentEnvId: number | null;
  deploying: Set<number>;
  onEnvChange: (envId: number) => void;
  onDeploy: (app: ApplicationConfig, remark: string) => Promise<void>;
}

/**
 * 环境标签页组件
 * 显示环境切换标签和应用列表
 */
export const EnvironmentTabs: React.FC<EnvironmentTabsProps> = React.memo(({
  team,
  currentEnvId,
  deploying,
  onEnvChange,
  onDeploy
}) => {
  const [searchValue, setSearchValue] = useState('');
  const currentEnv = team.environments.find(e => e.environmentId === currentEnvId);

  // 过滤应用列表
  const filteredEnvironments = useMemo(() => {
    if (!searchValue.trim()) {
      return team.environments;
    }
    
    const searchLower = searchValue.toLowerCase();
    return team.environments.map(env => ({
      ...env,
      applications: env.applications.filter(app =>
        app.applicationCode?.toLowerCase().includes(searchLower) ||
        app.applicationName?.toLowerCase().includes(searchLower)
      )
    }));
  }, [team.environments, searchValue]);

  return (
    <Tabs value={currentEnvId?.toString()} onValueChange={(value) => onEnvChange(Number(value))}>
      {/* 现代化 TAB 头部 */}
      <div className="bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b">
        <div className="flex items-center justify-between px-6 pt-4 pb-2">
          <div className="flex items-center gap-3">
            <div className="h-8 w-1 bg-primary rounded-full" />
            <h3 className="text-lg font-semibold">部署环境</h3>
          </div>
          <div className="flex items-center gap-2 text-sm text-muted-foreground h-[32px]">
            {currentEnv && currentEnv.requiresApproval && currentEnv.approvers.length > 0 && (
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-md bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800">
                <Shield className="h-3.5 w-3.5 text-amber-600" />
                <span className="text-amber-900 dark:text-amber-200 font-medium">
                  需审批: {currentEnv.approvers.map((a) => a.realName).join('、')}
                </span>
              </div>
            )}
          </div>
        </div>
        
        <div className="px-6 pb-3 space-y-3">
          <div className="inline-flex h-11 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground gap-1">
            {team.environments.map((env) => {
              const filteredEnv = filteredEnvironments.find(e => e.environmentId === env.environmentId);
              const displayCount = searchValue.trim() ? (filteredEnv?.applications.length || 0) : env.applications.length;
              
              return (
                <button
                  key={env.environmentId}
                  onClick={() => onEnvChange(env.environmentId)}
                  className={`
                    inline-flex items-center justify-center whitespace-nowrap rounded-md px-4 py-2
                    text-sm font-medium ring-offset-background transition-all
                    focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2
                    disabled:pointer-events-none disabled:opacity-50
                    ${currentEnvId === env.environmentId
                      ? 'bg-background text-foreground shadow-sm'
                      : 'hover:bg-background/50 hover:text-foreground'
                    }
                  `}
                >
                  <div className="flex items-center gap-2">
                    {env.requiresApproval ? (
                      <Shield className={`h-3.5 w-3.5 ${currentEnvId === env.environmentId ? 'text-amber-600' : 'text-amber-500/60'}`} />
                    ) : (
                      <CheckCircle2 className={`h-3.5 w-3.5 ${currentEnvId === env.environmentId ? 'text-green-600' : 'text-green-500/60'}`} />
                    )}
                    <span>{env.environmentName}</span>
                    <span className={`
                      ml-1 rounded-full px-2 py-0.5 text-xs font-semibold
                      ${currentEnvId === env.environmentId
                        ? 'bg-primary/10 text-primary'
                        : 'bg-muted-foreground/10 text-muted-foreground'
                      }
                    `}>
                      {displayCount}
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
          
          {/* 搜索框 */}
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="搜索应用名称或编码..."
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              className="pl-9 pr-9 h-9"
            />
            {searchValue && (
              <Button
                variant="ghost"
                size="sm"
                className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0"
                onClick={() => setSearchValue('')}
              >
                <X className="h-3.5 w-3.5" />
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 内容区域 */}
      {filteredEnvironments.map((env) => (
        <TabsContent key={env.environmentId} value={env.environmentId.toString()} className="mt-0 focus-visible:ring-0 focus-visible:ring-offset-0">
          <div className="p-6 min-h-[400px]">
            {env.applications.length === 0 ? (
              <Card>
                <CardContent className="flex flex-col items-center justify-center py-16">
                  <div className="rounded-full bg-muted p-6 mb-4">
                    <Package className="h-12 w-12 text-muted-foreground" />
                  </div>
                  <h3 className="text-lg font-semibold mb-2">
                    {searchValue.trim() ? '未找到匹配的应用' : '暂无可部署应用'}
                  </h3>
                  <p className="text-sm text-muted-foreground">
                    {searchValue.trim() 
                      ? `没有找到包含"${searchValue}"的应用`
                      : `环境「${env.environmentName}」暂未配置任何应用`
                    }
                  </p>
                  {searchValue.trim() && (
                    <Button
                      variant="outline"
                      size="sm"
                      className="mt-4"
                      onClick={() => setSearchValue('')}
                    >
                      <X className="h-3.5 w-3.5 mr-1" />
                      清除搜索
                    </Button>
                  )}
                </CardContent>
              </Card>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-4">
                {env.applications.map((app) => (
                  <ApplicationCard
                    key={app.teamApplicationId}
                    app={app}
                    environment={env}
                    teamId={team.teamId}
                    onDeploy={onDeploy}
                    isDeploying={deploying.has(app.teamApplicationId)}
                  />
                ))}
              </div>
            )}
          </div>
        </TabsContent>
      ))}
    </Tabs>
  );
});

EnvironmentTabs.displayName = 'EnvironmentTabs';
