
import React, { useState } from 'react';
import { Search, Filter, Plus, Trash2, Key, Server, Ear, Globe, Languages } from 'lucide-react';
import { Button, Input, TableHeader, TableRow, TableHead, TableCell, Dialog, Badge } from '../components/UI';
import { mockASRModels } from '../services/mockData';
import { ASRModel } from '../types';

export const ASRLibraryPage: React.FC = () => {
  const [models, setModels] = useState<ASRModel[]>(mockASRModels);
  const [searchTerm, setSearchTerm] = useState('');
  const [vendorFilter, setVendorFilter] = useState<string>('all');
  const [langFilter, setLangFilter] = useState<string>('all');
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);

  // Form State
  const [newModel, setNewModel] = useState<Partial<ASRModel>>({
    vendor: 'OpenAI Compatible',
    language: 'zh'
  });

  const filteredModels = models.filter(m => {
    const matchesSearch = m.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesVendor = vendorFilter === 'all' || m.vendor === vendorFilter;
    const matchesLang = langFilter === 'all' || m.language === langFilter || (langFilter !== 'all' && m.language === 'Multi-lingual');
    return matchesSearch && matchesVendor && matchesLang;
  });

  const handleAddModel = () => {
    if (!newModel.name || !newModel.baseUrl || !newModel.apiKey) {
      alert("请填写完整信息");
      return;
    }
    
    const model: ASRModel = {
      id: `asr_${Date.now()}`,
      name: newModel.name,
      vendor: newModel.vendor as 'OpenAI Compatible',
      language: newModel.language || 'zh',
      baseUrl: newModel.baseUrl,
      apiKey: newModel.apiKey
    };

    setModels([model, ...models]);
    setIsAddModalOpen(false);
    setNewModel({ vendor: 'OpenAI Compatible', language: 'zh', name: '', baseUrl: '', apiKey: '' });
  };

  const handleDeleteModel = (id: string) => {
    if (confirm('确认删除该语音识别模型吗？')) {
      setModels(prev => prev.filter(m => m.id !== id));
    }
  };

  const maskApiKey = (key: string) => {
    if (!key || key.length < 8) return '********';
    return `${key.substring(0, 3)}****${key.substring(key.length - 4)}`;
  };

  return (
    <div className="space-y-6 animate-in fade-in py-4 pb-10">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold tracking-tight text-white">语音识别</h1>
        <Button onClick={() => setIsAddModalOpen(true)} className="shadow-[0_0_15px_rgba(6,182,212,0.4)]">
            <Plus className="mr-2 h-4 w-4" /> 添加模型
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 bg-card/50 p-4 rounded-lg border border-white/5 shadow-sm">
         <div className="relative col-span-1 md:col-span-2">
             <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
             <Input 
                placeholder="搜索模型名称..." 
                className="pl-9 border-0 bg-white/5" 
                value={searchTerm} 
                onChange={e => setSearchTerm(e.target.value)}
             />
         </div>
         <div className="flex items-center space-x-2">
            <Filter className="h-4 w-4 text-muted-foreground" />
            <select 
                className="flex h-9 w-full rounded-md border-0 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
                value={vendorFilter}
                onChange={(e) => setVendorFilter(e.target.value)}
            >
                <option value="all">所有接口类型</option>
                <option value="OpenAI Compatible">OpenAI Compatible</option>
            </select>
         </div>
         <div className="flex items-center space-x-2">
            <select 
                className="flex h-9 w-full rounded-md border-0 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&>option]:bg-card text-foreground"
                value={langFilter}
                onChange={(e) => setLangFilter(e.target.value)}
            >
                <option value="all">所有语言</option>
                <option value="zh">中文 (Chinese)</option>
                <option value="en">英文 (English)</option>
                <option value="Multi-lingual">多语言 (Multi-lingual)</option>
            </select>
         </div>
      </div>

      <div className="rounded-md border border-white/5 bg-card/40 backdrop-blur-md overflow-hidden">
        <table className="w-full text-sm">
          <TableHeader>
            <TableRow>
              <TableHead>模型名称</TableHead>
              <TableHead>接口类型</TableHead>
              <TableHead>语言</TableHead>
              <TableHead>Base URL</TableHead>
              <TableHead>API Key</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <tbody>
            {filteredModels.map(model => (
              <TableRow key={model.id}>
                <TableCell className="font-medium text-white flex items-center">
                    <Ear className="w-4 h-4 mr-2 text-primary" />
                    {model.name}
                </TableCell>
                <TableCell>
                    <Badge variant="outline">{model.vendor}</Badge>
                </TableCell>
                <TableCell>
                    <Badge variant="default" className="bg-purple-500/10 text-purple-400 border-purple-500/20">
                        {model.language}
                    </Badge>
                </TableCell>
                <TableCell className="font-mono text-xs text-muted-foreground">
                    {model.baseUrl}
                </TableCell>
                <TableCell className="font-mono text-xs text-muted-foreground">
                    {maskApiKey(model.apiKey)}
                </TableCell>
                <TableCell className="text-right">
                    <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => handleDeleteModel(model.id)}
                        className="text-muted-foreground hover:text-destructive transition-colors"
                    >
                        <Trash2 className="h-4 w-4" />
                    </Button>
                </TableCell>
              </TableRow>
            ))}
             {filteredModels.length === 0 && (
                 <TableRow>
                     <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">暂无语音识别模型</TableCell>
                 </TableRow>
             )}
          </tbody>
        </table>
      </div>

      <Dialog
        isOpen={isAddModalOpen}
        onClose={() => setIsAddModalOpen(false)}
        title="添加语音识别模型"
        footer={
          <>
            <Button variant="ghost" onClick={() => setIsAddModalOpen(false)}>取消</Button>
            <Button onClick={handleAddModel}>确认添加</Button>
          </>
        }
      >
        <div className="space-y-4">
          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block">接口类型 (Interface Type)</label>
            <select 
                className="flex h-10 w-full rounded-md border border-white/10 bg-white/5 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 text-foreground appearance-none cursor-pointer [&>option]:bg-card"
                value={newModel.vendor}
                onChange={e => setNewModel({...newModel, vendor: e.target.value as any})}
            >
                <option value="OpenAI Compatible">OpenAI Compatible</option>
            </select>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block">支持语言 (Language)</label>
            <div className="flex bg-white/5 p-1 rounded-lg border border-white/10">
                {(['zh', 'en', 'Multi-lingual'] as const).map(l => (
                    <button 
                        key={l}
                        onClick={() => setNewModel({...newModel, language: l})}
                        className={`flex-1 flex items-center justify-center py-1.5 text-xs font-bold rounded-md transition-all ${newModel.language === l ? 'bg-primary text-primary-foreground shadow-lg' : 'text-muted-foreground hover:text-foreground'}`}
                    >
                        {l === 'zh' && <span className="mr-1">🇨🇳</span>}
                        {l === 'en' && <span className="mr-1">🇺🇸</span>}
                        {l === 'Multi-lingual' && <Globe className="w-3 h-3 mr-1.5" />}
                        {l === 'zh' ? '中文' : l === 'en' ? '英文' : '多语言'}
                    </button>
                ))}
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block">模型名称 (Model Name)</label>
            <Input 
                value={newModel.name} 
                onChange={e => setNewModel({...newModel, name: e.target.value})} 
                placeholder="例如: whisper-1, funasr" 
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block flex items-center">
                <Server className="w-3 h-3 mr-1.5" /> Base URL
            </label>
            <Input 
                value={newModel.baseUrl} 
                onChange={e => setNewModel({...newModel, baseUrl: e.target.value})} 
                placeholder="https://api.openai.com/v1" 
                className="font-mono text-xs"
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-muted-foreground uppercase tracking-widest block flex items-center">
                <Key className="w-3 h-3 mr-1.5" /> API Key
            </label>
            <Input 
                type="password"
                value={newModel.apiKey} 
                onChange={e => setNewModel({...newModel, apiKey: e.target.value})} 
                placeholder="sk-..." 
                className="font-mono text-xs"
            />
          </div>
        </div>
      </Dialog>
    </div>
  );
};
