'use client';

import React, { useState, useEffect } from 'react';
import { Loader2, Check, AlertCircle, ExternalLink, Shield, Eye, EyeOff, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  createApiKey,
  updateApiKey,
  deleteApiKey,
  verifyApiKey,
  type ApiKey,
} from '@/lib/api/userApiKeys';
import { ProviderIcon } from '@/components/common/ProviderIcon';

interface ProviderConfig {
  id: string;
  name: string;
  description: string;
  fields: {
    name: string;
    label: string;
    placeholder: string;
    required: boolean;
    type?: 'password' | 'text';
  }[];
  helpUrl?: string;
}

interface ApiKeyFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  editKey?: ApiKey | null;
  existingProviders?: string[];
  defaultProvider?: string;
  providerConfigs?: ProviderConfig[];
}

export function ApiKeyForm({
  isOpen,
  onClose,
  onSuccess,
  editKey,
  existingProviders = [],
  defaultProvider = '',
  providerConfigs = []
}: ApiKeyFormProps) {
  const [provider, setProvider] = useState(editKey?.provider || '');
  const [name, setName] = useState(editKey?.name || '');
  const [fieldValues, setFieldValues] = useState<Record<string, string>>({});
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isVerifying, setIsVerifying] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [verifyResult, setVerifyResult] = useState<{ success: boolean; message: string } | null>(null);

  const isEditing = !!editKey;

  // Local helper to get provider config from passed providerConfigs
  const getProviderConfig = (providerId: string): ProviderConfig | undefined => {
    return providerConfigs.find(p => p.id === providerId);
  };

  const providerConfig = getProviderConfig(provider);

  useEffect(() => {
    if (isOpen) {
      if (editKey) {
        setProvider(editKey.provider);
        setName(editKey.name || '');
        setFieldValues(editKey.extraConfig || {});
      } else {
        setProvider(defaultProvider);
        setName('');
        setFieldValues({});
        setShowPasswords({});
      }
      setError(null);
      setVerifyResult(null);
    }
  }, [isOpen, editKey, defaultProvider]);

  const handleFieldChange = (fieldName: string, value: string) => {
    setFieldValues(prev => ({ ...prev, [fieldName]: value }));
    // Clear error when user types
    if (error) setError(null);
  };

  const togglePasswordVisibility = (fieldName: string) => {
    setShowPasswords(prev => ({ ...prev, [fieldName]: !prev[fieldName] }));
  };

  const validateFields = (): boolean => {
    if (!providerConfig) {
      setError('请选择提供商');
      return false;
    }

    for (const field of providerConfig.fields) {
      if (field.required && !fieldValues[field.name]?.trim()) {
        setError(`${field.label} 是必填项`);
        return false;
      }
    }
    return true;
  };

  const buildRequestData = () => {
    const primaryKey = fieldValues.apiKey || Object.values(fieldValues)[0] || '';
    const extraConfig: Record<string, string> = {};

    for (const [key, value] of Object.entries(fieldValues)) {
      if (key !== 'apiKey' && value) {
        extraConfig[key] = value;
      }
    }

    return {
      provider,
      apiKey: primaryKey,
      name: name || undefined,
      extraConfig: Object.keys(extraConfig).length > 0 ? extraConfig : undefined,
    };
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!validateFields()) return;

    setIsSubmitting(true);
    try {
      const requestData = buildRequestData();
      if (isEditing && editKey) {
        await updateApiKey(editKey.id, requestData);
      } else {
        await createApiKey(requestData);
      }
      onSuccess();
      resetForm();
    } catch (err: any) {
      setError(err.response?.data?.message || err.response?.data?.detail || err.message || '操作失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleVerify = async () => {
    if (!validateFields()) return;

    setIsVerifying(true);
    setVerifyResult(null);

    try {
      if (isEditing && editKey) {
        const result = await verifyApiKey(editKey.id);
        setVerifyResult({
          success: result.valid,
          message: result.message || (result.valid ? '✓ 密钥验证成功，可以正常使用' : result.message || '✗ 验证失败'),
        });
      } else {
        const primaryKey = fieldValues.apiKey || Object.values(fieldValues)[0] || '';
        const isFormatValid = primaryKey.length >= 10;
        setVerifyResult({
          success: isFormatValid,
          message: isFormatValid
            ? '✓ 密钥格式看起来有效，保存后可进行实际验证'
            : '✗ 密钥格式不正确（长度至少需要10个字符）',
        });
      }
    } catch (err: any) {
      setVerifyResult({
        success: false,
        message: err.response?.data?.message || err.response?.data?.detail || err.message || '验证失败',
      });
    } finally {
      setIsVerifying(false);
    }
  };

  const resetForm = () => {
    setProvider('');
    setName('');
    setFieldValues({});
    setShowPasswords({});
    setError(null);
    setVerifyResult(null);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  const handleDelete = async () => {
    if (!editKey) return;

    setIsDeleting(true);
    try {
      await deleteApiKey(editKey.id);
      onSuccess();
      resetForm();
    } catch (err: any) {
      setError(err.response?.data?.message || err.response?.data?.detail || err.message || '删除失败');
    } finally {
      setIsDeleting(false);
      setShowDeleteConfirm(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-hidden flex flex-col p-0 gap-0">
        <DialogHeader className="px-6 py-4 border-b">
          <DialogTitle className="text-lg font-semibold">
            {isEditing ? '编辑密钥' : '添加密钥'}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto pr-2 space-y-6 py-6 px-6">
          {/* Alert Messages */}
          {error && (
            <div className="flex items-start gap-2 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
              <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {verifyResult && (
            <div className={`flex items-start gap-2 p-3 rounded-lg text-sm ${
              verifyResult.success
                ? 'bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 dark:text-emerald-400'
                : 'bg-destructive/10 text-destructive'
            }`}>
              {verifyResult.success ? (
                <Check className="w-4 h-4 mt-0.5 shrink-0" />
              ) : (
                <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
              )}
              <span>{verifyResult.message}</span>
            </div>
          )}

          {/* Basic Information Section */}
          <section className="space-y-4">
            <h3 className="text-sm font-semibold text-foreground uppercase tracking-wider flex items-center gap-2">
              <div className="w-1 h-4 bg-primary rounded-full" />
              基本信息
            </h3>

            <div className="space-y-4 pl-3">
              {/* Provider Selection - Show dropdown only when no provider is pre-selected */}
              {defaultProvider ? (
                /* Provider is pre-selected from card click - show read-only info */
                <div className="space-y-2">
                  <Label className="text-sm font-medium text-muted-foreground">
                    提供商
                  </Label>
                  {providerConfig && (
                    <div className="flex items-center gap-3 p-3 bg-muted/30 rounded-lg border border-border">
                      <div className="w-8 h-8 flex items-center justify-center shrink-0">
                        <ProviderIcon provider={providerConfig.id} className="w-6 h-6" />
                      </div>
                      <div className="flex flex-col">
                        <span className="font-medium text-foreground">{providerConfig.name}</span>
                        <span className="text-xs text-muted-foreground">{providerConfig.description}</span>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                /* No provider pre-selected - show dropdown for selection */
                <div className="space-y-2">
                  <Label htmlFor="provider" className="text-sm font-medium flex items-center gap-1">
                    选择提供商
                    <span className="text-destructive">*</span>
                  </Label>
                  <Select
                    value={provider}
                    onValueChange={setProvider}
                    disabled={isEditing || isSubmitting}
                  >
                    <SelectTrigger id="provider" className="h-11">
                      <SelectValue placeholder="请选择 AI 服务提供商">
                        {provider && providerConfig && (
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{providerConfig.name}</span>
                          </div>
                        )}
                      </SelectValue>
                    </SelectTrigger>
                    <SelectContent className="max-h-[300px] bg-background border-border">
                      {providerConfigs.map((p) => {
                        const isAlreadyConfigured = existingProviders.includes(p.id);
                        return (
                          <SelectItem
                            key={p.id}
                            value={p.id}
                            disabled={isAlreadyConfigured}
                            className="py-3"
                          >
                            <div className="flex items-center justify-between w-full gap-4 pr-2">
                              <div className="flex items-center gap-3">
                                <div className="w-8 h-8 flex items-center justify-center shrink-0">
                                  <ProviderIcon provider={p.id} className="w-6 h-6" />
                                </div>
                                <div className="flex flex-col">
                                  <span className={isAlreadyConfigured ? 'text-muted-foreground' : 'font-medium'}>
                                    {p.name}
                                  </span>
                                  <span className="text-xs text-muted-foreground">{p.description}</span>
                                </div>
                              </div>
                              {isAlreadyConfigured && (
                                <Badge variant="secondary" className="bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/10 shrink-0 dark:text-emerald-400">
                                  <Check className="w-3 h-3 mr-1" />
                                  已配置
                                </Badge>
                              )}
                            </div>
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Display Name */}
              <div className="space-y-2">
                <Label htmlFor="name" className="text-sm font-medium">显示名称</Label>
                <Input
                  id="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="例如：我的工作 Key"
                  disabled={isSubmitting}
                  className="h-11"
                />
                <p className="text-xs text-muted-foreground">
                  用于区分不同的密钥，方便管理
                </p>
              </div>
            </div>
          </section>

          <div className="h-px bg-border" />

          {/* Provider Configuration Section */}
          {providerConfig && (
            <section className="space-y-4">
              <h3 className="text-sm font-semibold text-foreground uppercase tracking-wider flex items-center gap-2">
                <div className="w-1 h-4 bg-primary rounded-full" />
                {providerConfig.name} 配置
              </h3>

              <div className="space-y-4 pl-3">
                <div className="grid grid-cols-2 gap-4">
                  {providerConfig.fields.map((field) => (
                    <div key={field.name} className="space-y-2">
                      <Label htmlFor={field.name} className="text-sm">
                        {field.label}
                        {field.required && <span className="text-destructive ml-1">*</span>}
                      </Label>
                      <div className="relative">
                        <Input
                          id={field.name}
                          type={showPasswords[field.name] ? 'text' : (field.type || 'text')}
                          value={fieldValues[field.name] || ''}
                          onChange={(e) => handleFieldChange(field.name, e.target.value)}
                          placeholder={field.placeholder}
                          disabled={isSubmitting}
                          required={field.required}
                          className="h-11 pr-10"
                        />
                        {/* Show/hide password toggle for sensitive fields */}
                        {(field.type === 'password' || field.name.toLowerCase().includes('key') || field.name.toLowerCase().includes('secret')) && (
                          <button
                            type="button"
                            onClick={() => togglePasswordVisibility(field.name)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                          >
                            {showPasswords[field.name] ? (
                              <EyeOff className="w-4 h-4" />
                            ) : (
                              <Eye className="w-4 h-4" />
                            )}
                          </button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>

                {/* Help Link */}
                {providerConfig.helpUrl && (
                  <a
                    href={providerConfig.helpUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center text-sm text-primary hover:text-primary/80 transition-colors"
                  >
                    <ExternalLink className="w-3.5 h-3.5 mr-1.5" />
                    如何获取 {providerConfig.name} 的密钥
                  </a>
                )}
              </div>
            </section>
          )}
        </form>

        {/* Footer Buttons */}
        <div className="flex items-center justify-between px-6 py-4 border-t bg-background">
          <div className="flex items-center gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={handleClose}
              disabled={isSubmitting || isDeleting}
              className="h-10 px-6"
            >
              取消
            </Button>
            {isEditing && (
              <Button
                type="button"
                variant="destructive"
                onClick={() => setShowDeleteConfirm(true)}
                disabled={isSubmitting || isDeleting}
                className="h-10 px-6"
              >
                {isDeleting ? (
                  <Loader2 className="w-4 h-4 animate-spin mr-1" />
                ) : (
                  <Trash2 className="w-4 h-4 mr-1" />
                )}
                删除
              </Button>
            )}
          </div>
          <div className="flex items-center gap-3">
            {providerConfig && (
              <Button
                type="button"
                variant="outline"
                onClick={handleVerify}
                disabled={isVerifying || isSubmitting || isDeleting}
                className="h-10 px-6"
              >
                {isVerifying ? (
                  <Loader2 className="w-4 h-4 animate-spin mr-1" />
                ) : (
                  <Shield className="w-4 h-4 mr-1" />
                )}
                验证
              </Button>
            )}
            <Button
              type="submit"
              disabled={isSubmitting || !provider || isDeleting}
              className="h-10 px-6"
              onClick={handleSubmit}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  {isEditing ? '保存中' : '添加中'}
                </>
              ) : (
                isEditing ? '保存' : '添加'
              )}
            </Button>
          </div>
        </div>
      </DialogContent>

      {/* Delete Confirmation Dialog */}
      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-destructive">
              <AlertCircle className="w-5 h-5" />
              确认删除
            </DialogTitle>
            <DialogDescription>
              您确定要删除 {providerConfig?.name || '该供应商'} 的密钥吗？
              此操作不可撤销，删除后将无法恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => setShowDeleteConfirm(false)}
              disabled={isDeleting}
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              确认删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Dialog>
  );
}
