import { Plus, Trash2, RefreshCw, Eye, EyeOff } from "lucide-react"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useLlmProviders } from "@/hooks/useConfig"
import { LlmProvider } from "@/types/config"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"

export function AIProviderTab() {
  const { data: providers, isLoading } = useLlmProviders();
  const [isAddOpen, setIsAddOpen] = useState(false);

  if (isLoading) {
    return <div>Loading providers...</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
           <h3 className="text-lg font-medium">已配置的服务商</h3>
           <p className="text-sm text-muted-foreground">管理连接到系统的 LLM API。</p>
        </div>
        <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> 添加 Provider</Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>添加 AI Provider</DialogTitle>
              <DialogDescription>
                配置新的 LLM 服务商连接信息。
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">名称</Label>
                <Input id="name" placeholder="e.g. OpenAI" className="col-span-3" />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="url" className="text-right">Base URL</Label>
                <Input id="url" placeholder="https://api.openai.com/v1" className="col-span-3" />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="key" className="text-right">API Key</Label>
                <Input id="key" type="password" className="col-span-3" />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" onClick={() => setIsAddOpen(false)}>保存</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-6 md:grid-cols-1 lg:grid-cols-2">
        {providers && Object.entries(providers).map(([id, provider]) => (
          <ProviderCard key={id} id={id} provider={provider} />
        ))}
      </div>
    </div>
  )
}

function ProviderCard({ id, provider }: { id: string, provider: LlmProvider }) {
  const [showKey, setShowKey] = useState(false);

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div className="space-y-1">
          <CardTitle className="text-xl">{provider.name}</CardTitle>
          <CardDescription className="font-mono text-xs truncate max-w-[250px]">
            {provider.api_base_url}
          </CardDescription>
        </div>
        <Badge variant="outline">{provider.models.length} Models</Badge>
      </CardHeader>
      <CardContent className="space-y-4 mt-4">
        <div className="space-y-2">
          <Label className="text-xs text-muted-foreground">API KEY</Label>
          <div className="flex items-center space-x-2">
            <Input 
              type={showKey ? "text" : "password"} 
              value={provider.api_key} 
              readOnly 
              className="h-8 font-mono text-xs bg-muted/50" 
            />
            <Button 
              variant="ghost" 
              size="icon" 
              className="h-8 w-8"
              onClick={() => setShowKey(!showKey)}
            >
              {showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </Button>
          </div>
        </div>

        <div className="space-y-2">
            <div className="flex items-center justify-between">
                <Label className="text-xs text-muted-foreground">ACTIVE MODELS</Label>
                <Button variant="ghost" size="sm" className="h-6 text-xs px-2">
                    <RefreshCw className="mr-1 h-3 w-3" /> 刷新列表
                </Button>
            </div>
            <div className="flex flex-wrap gap-2">
                {provider.models.map(model => (
                    <Badge key={model.model_id} variant="secondary" className="text-xs font-normal">
                        {model.name || model.model_id}
                    </Badge>
                ))}
            </div>
        </div>
      </CardContent>
      <CardFooter className="justify-end pt-2">
         <Button variant="ghost" size="sm" className="text-destructive hover:text-destructive hover:bg-destructive/10">
            <Trash2 className="mr-2 h-4 w-4" /> 删除
         </Button>
      </CardFooter>
    </Card>
  )
}
