'use client';

import { useState, useEffect, useCallback } from 'react';
import { Key, Eye, EyeOff, Trash2, Check, Shield, AlertCircle, Loader2 } from 'lucide-react';
import { listProviderKeys, saveProviderKey, deleteProviderKey, ProviderKeyInfo } from '@client/api/provider-keys';
import { useLanguage } from '@client/contexts/LanguageContext';
import ConfirmModal from '@client/components/ui/ConfirmModal';

export default function ProviderKeysTab() {
  const { t } = useLanguage();
  const [keys, setKeys] = useState<ProviderKeyInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState<string | null>(null);
  const [editingProvider, setEditingProvider] = useState<string | null>(null);
  const [newKeyValue, setNewKeyValue] = useState('');
  const [showKey, setShowKey] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<string | null>(null);

  const fetchKeys = useCallback(async () => {
    try {
      setLoading(true);
      const data = await listProviderKeys();
      setKeys(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : t('providerKeys.errors.load', 'Failed to load API keys'));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchKeys(); }, [fetchKeys]);

  const handleSave = async (providerName: string) => {
    if (!newKeyValue.trim()) return;
    try {
      setSaving(providerName);
      setError(null);
      await saveProviderKey(providerName, newKeyValue.trim());
      setSuccess(t('providerKeys.success.saved', '{name} key saved', { name: keys.find(k => k.provider_name === providerName)?.display_name ?? providerName }));
      setEditingProvider(null);
      setNewKeyValue('');
      setShowKey(false);
      await fetchKeys();
      setTimeout(() => setSuccess(null), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : t('providerKeys.errors.save', 'Failed to save key'));
    } finally {
      setSaving(null);
    }
  };

  const handleDelete = async (providerName: string) => {
    try {
      setSaving(providerName);
      setError(null);
      await deleteProviderKey(providerName);
      setSuccess(t('providerKeys.success.removed', '{name} key removed', { name: keys.find(k => k.provider_name === providerName)?.display_name ?? providerName }));
      setDeleteTarget(null);
      await fetchKeys();
      setTimeout(() => setSuccess(null), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : t('providerKeys.errors.delete', 'Failed to delete key'));
    } finally {
      setSaving(null);
    }
  };

  const startEditing = (providerName: string) => {
    setEditingProvider(providerName);
    setNewKeyValue('');
    setShowKey(false);
    setError(null);
  };

  const cancelEditing = () => {
    setEditingProvider(null);
    setNewKeyValue('');
    setShowKey(false);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="animate-spin mr-2" size={20} />
        <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('providerKeys.loading', 'Loading API keys...')}</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-start gap-3 p-4 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
        <Shield size={20} className="mt-0.5 flex-shrink-0" style={{ color: 'hsl(var(--primary))' }} />
        <div>
          <h3 className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('providerKeys.byok.title', 'Bring Your Own Keys (BYOK)')}</h3>
          <p className="text-sm mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('providerKeys.byok.description', 'Add your own API keys for AI providers. Keys are encrypted at rest using AES-256-GCM.')}
          </p>
        </div>
      </div>

      {error && (
        <div className="flex items-center gap-2 p-3 rounded-lg text-sm" style={{ backgroundColor: 'hsl(0, 84%, 95%)', color: 'hsl(0, 84%, 40%)' }}>
          <AlertCircle size={16} />
          {error}
        </div>
      )}

      {success && (
        <div className="flex items-center gap-2 p-3 rounded-lg text-sm" style={{ backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(142, 72%, 29%)' }}>
          <Check size={16} />
          {success}
        </div>
      )}

      <div className="space-y-3">
        {keys.map(provider => (
          <div
            key={provider.provider_name}
            className="rounded-lg p-4"
            style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <Key size={18} style={{ color: provider.is_active ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }} />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                      {provider.display_name}
                    </span>
                    {provider.is_active && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-medium" style={{ backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(142, 72%, 29%)' }}>
                        {t('providerKeys.active', 'Active')}
                      </span>
                    )}
                    {!provider.is_active && provider.has_env_fallback && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-medium" style={{ backgroundColor: 'hsl(210, 100%, 95%)', color: 'hsl(210, 100%, 40%)' }}>
                        {t('providerKeys.systemDefault', 'System Default')}
                      </span>
                    )}
                  </div>
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {provider.description}
                    {provider.is_active && provider.key_hint && (
                      <span className="ml-2 font-mono">{provider.key_hint}</span>
                    )}
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2">
                {provider.is_active && (
                  <button
                    onClick={() => setDeleteTarget(provider.provider_name)}
                    className="p-2 rounded-lg hover:bg-red-50 transition-colors"
                    aria-label={t('providerKeys.removeKey', 'Remove key')}
                  >
                    <Trash2 size={16} style={{ color: 'hsl(0, 84%, 50%)' }} />
                  </button>
                )}
                <button
                  onClick={() => startEditing(provider.provider_name)}
                  className="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
                  style={{
                    backgroundColor: provider.is_active ? 'hsl(var(--muted))' : 'hsl(var(--primary))',
                    color: provider.is_active ? 'hsl(var(--foreground))' : 'white',
                  }}
                >
                  {provider.is_active ? t('providerKeys.update', 'Update') : t('providerKeys.addKey', 'Add Key')}
                </button>
              </div>
            </div>

            {editingProvider === provider.provider_name && (
              <div className="mt-4 pt-4" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <input
                      type={showKey ? 'text' : 'password'}
                      value={newKeyValue}
                      onChange={e => setNewKeyValue(e.target.value)}
                      placeholder={t('providerKeys.keyPlaceholder', 'Enter your {name} API key', { name: provider.display_name })}
                      className="w-full px-3 py-2 pr-10 text-sm rounded-lg border outline-none font-mono"
                      style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                      autoFocus
                    />
                    <button
                      onClick={() => setShowKey(!showKey)}
                      className="absolute right-2 top-1/2 -translate-y-1/2 p-1"
                      type="button"
                    >
                      {showKey ? <EyeOff size={16} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <Eye size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    </button>
                  </div>
                  <button
                    onClick={() => handleSave(provider.provider_name)}
                    disabled={!newKeyValue.trim() || saving === provider.provider_name}
                    className="px-4 py-2 rounded-lg text-sm font-medium text-white transition-colors disabled:opacity-50"
                    style={{ backgroundColor: 'hsl(var(--primary))' }}
                  >
                    {saving === provider.provider_name ? <Loader2 className="animate-spin" size={16} /> : t('common.save', 'Save')}
                  </button>
                  <button
                    onClick={cancelEditing}
                    className="px-3 py-2 rounded-lg text-sm transition-colors"
                    style={{ color: 'hsl(var(--muted-foreground))' }}
                  >
                    {t('common.cancel', 'Cancel')}
                  </button>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      <ConfirmModal
        isOpen={!!deleteTarget}
        title={t('providerKeys.removeModal.title', 'Remove API Key')}
        description={t('providerKeys.removeModal.message', 'Are you sure you want to remove this API key? This provider will stop working for your restaurant.')}
        confirmLabel={t('providerKeys.removeModal.confirm', 'Remove')}
        variant="danger"
        onConfirm={() => { if (deleteTarget) handleDelete(deleteTarget); }}
        onClose={() => setDeleteTarget(null)}
      />

    </div>
  );
}
