import React, { useState } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Search, Check, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { RepositoryBranchResponse } from '@/pages/Resource/Git/List/types';

interface GitConfigSelectorProps {
  label: string; // "源" 或 "目标"
  // Git系统
  gitSystems: any[];
  selectedSystemId: number | null;
  onSystemChange: (systemId: number) => void;
  // 仓库项目
  repoProjects: any[];
  loadingRepoProjects: boolean;
  selectedProjectId: number | null;
  onProjectChange: (projectId: number) => void;
  // 分支
  branches: RepositoryBranchResponse[];
  loadingBranches: boolean;
  selectedBranch: string;
  onBranchChange: (branch: string) => void;
}

export const GitConfigSelector: React.FC<GitConfigSelectorProps> = ({
  label,
  gitSystems,
  selectedSystemId,
  onSystemChange,
  repoProjects,
  loadingRepoProjects,
  selectedProjectId,
  onProjectChange,
  branches,
  loadingBranches,
  selectedBranch,
  onBranchChange,
}) => {
  const [projectSearchValue, setProjectSearchValue] = useState('');
  const [projectPopoverOpen, setProjectPopoverOpen] = useState(false);
  const [branchSearchValue, setBranchSearchValue] = useState('');
  const [branchPopoverOpen, setBranchPopoverOpen] = useState(false);

  // 过滤分支
  const filteredBranches = branches.filter(branch =>
    branch.name.toLowerCase().includes(branchSearchValue.toLowerCase())
  );

  return (
    <div className="space-y-2">
      <Label className="text-sm font-semibold">{label}Git配置</Label>
      <div className="grid grid-cols-3 gap-4">
        {/* 代码系统 */}
        <div className="space-y-2">
          <Label className="text-xs text-muted-foreground">{label}代码系统</Label>
          <Select
            value={selectedSystemId?.toString() || ''}
            onValueChange={(value) => onSystemChange(Number(value))}
          >
            <SelectTrigger>
              <SelectValue placeholder="选择系统" />
            </SelectTrigger>
            <SelectContent>
              {gitSystems.length === 0 ? (
                <div className="p-4 text-center text-sm text-muted-foreground">
                  暂无可用的Git系统
                </div>
              ) : (
                gitSystems.map((system) => (
                  <SelectItem key={system.id} value={system.id.toString()}>
                    {system.name}
                  </SelectItem>
                ))
              )}
            </SelectContent>
          </Select>
        </div>

        {/* 仓库项目 */}
        <div className="space-y-2">
          <Label className="text-xs text-muted-foreground">{label}仓库项目</Label>
          {selectedSystemId ? (
            <Popover open={projectPopoverOpen} onOpenChange={setProjectPopoverOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  disabled={loadingRepoProjects || repoProjects.length === 0}
                  className={cn(
                    'w-full justify-between',
                    !selectedProjectId && 'text-muted-foreground'
                  )}
                >
                  {selectedProjectId
                    ? (() => {
                        const selectedProject = repoProjects.find(
                          (p) => p.repoProjectId === selectedProjectId
                        );
                        return selectedProject
                          ? (selectedProject.repoGroupName
                              ? `${selectedProject.repoGroupName} / ${selectedProject.name}`
                              : selectedProject.name)
                          : '选择项目';
                      })()
                    : loadingRepoProjects
                    ? '加载中...'
                    : repoProjects.length === 0
                    ? '暂无项目'
                    : '选择项目'}
                  <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
                <div className="flex items-center border-b px-3">
                  <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                  <input
                    placeholder="搜索项目..."
                    className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
                    value={projectSearchValue}
                    onChange={(e) => setProjectSearchValue(e.target.value)}
                  />
                </div>
                <ScrollArea className="h-[200px]">
                  <div className="p-1">
                    {repoProjects
                      .filter(
                        (project) =>
                          project.name.toLowerCase().includes(projectSearchValue.toLowerCase()) ||
                          project.repoGroupName?.toLowerCase().includes(projectSearchValue.toLowerCase())
                      )
                      .map((project) => (
                        <div
                          key={project.repoProjectId}
                          className={cn(
                            'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground',
                            project.repoProjectId === selectedProjectId && 'bg-accent text-accent-foreground'
                          )}
                          onClick={() => {
                            onProjectChange(project.repoProjectId);
                            setProjectSearchValue('');
                            setProjectPopoverOpen(false);
                          }}
                        >
                          <div className="flex-1 truncate">
                            {project.repoGroupName && (
                              <span className="text-muted-foreground">{project.repoGroupName} / </span>
                            )}
                            {project.name}
                          </div>
                          {project.repoProjectId === selectedProjectId && <Check className="ml-2 h-4 w-4" />}
                        </div>
                      ))}
                  </div>
                </ScrollArea>
              </PopoverContent>
            </Popover>
          ) : (
            <Input placeholder="请先选择系统" disabled />
          )}
        </div>

        {/* 分支 */}
        <div className="space-y-2">
          <Label className="text-xs text-muted-foreground">{label}分支</Label>
          {selectedProjectId ? (
            <Popover open={branchPopoverOpen} onOpenChange={setBranchPopoverOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  disabled={loadingBranches || branches.length === 0}
                  className={cn('w-full justify-between', !selectedBranch && 'text-muted-foreground')}
                >
                  {selectedBranch
                    ? (() => {
                        const selectedBranchObj = branches.find((b) => b.name === selectedBranch);
                        return (
                          <span className="flex items-center gap-2 truncate">
                            {selectedBranchObj?.name}
                            {selectedBranchObj?.isDefaultBranch && (
                              <span className="text-xs text-muted-foreground">(默认)</span>
                            )}
                          </span>
                        );
                      })()
                    : loadingBranches
                    ? '加载中...'
                    : branches.length === 0
                    ? '无分支'
                    : '选择分支'}
                  <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0">
                <div className="flex items-center border-b px-3">
                  <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                  <input
                    placeholder="搜索分支..."
                    className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
                    value={branchSearchValue}
                    onChange={(e) => setBranchSearchValue(e.target.value)}
                  />
                </div>
                <ScrollArea className="h-[200px]">
                  <div className="p-1">
                    {filteredBranches.length === 0 ? (
                      <div className="p-4 text-center text-sm text-muted-foreground">未找到分支</div>
                    ) : (
                      filteredBranches.map((branch) => (
                        <div
                          key={branch.id}
                          className={cn(
                            'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent',
                            branch.name === selectedBranch && 'bg-accent'
                          )}
                          onClick={() => {
                            onBranchChange(branch.name);
                            setBranchSearchValue('');
                            setBranchPopoverOpen(false);
                          }}
                        >
                          <span className="flex-1 truncate">
                            {branch.name}
                            {branch.isDefaultBranch && (
                              <span className="ml-2 text-xs text-muted-foreground">(默认)</span>
                            )}
                          </span>
                          {branch.name === selectedBranch && <Check className="ml-2 h-4 w-4" />}
                        </div>
                      ))
                    )}
                  </div>
                </ScrollArea>
              </PopoverContent>
            </Popover>
          ) : (
            <Input placeholder="请先选择项目" disabled />
          )}
        </div>
      </div>
    </div>
  );
};
