'use client';

import { useState, useEffect, useCallback } from 'react';
import { Key, Eye, EyeOff, Trash2, Check, Shield, AlertCircle, Loader2, Mail, ChevronDown } 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';

interface BranchSmtpForm {
  smtp_host: string;
  smtp_port: string;
  smtp_user: string;
  smtp_pass: string;
  smtp_from: string;
}

const EMPTY_SMTP: BranchSmtpForm = { smtp_host: '', smtp_port: '587', smtp_user: '', smtp_pass: '', smtp_from: '' };

function SmtpSection() {
  const { t } = useLanguage();
  const [branches, setBranches] = useState<{ id: string; name: string; smtpConfigured: boolean }[]>([]);
  const [selectedBranchId, setSelectedBranchId] = useState<string>('');
  const [form, setForm] = useState<BranchSmtpForm>(EMPTY_SMTP);
  const [showPass, setShowPass] = useState(false);
  const [loadingBranches, setLoadingBranches] = useState(true);
  const [loadingSmtp, setLoadingSmtp] = useState(false);
  const [saving, setSaving] = useState(false);
  const [clearing, setClearing] = useState(false);
  const [smtpError, setSmtpError] = useState<string | null>(null);
  const [smtpSuccess, setSmtpSuccess] = useState<string | null>(null);
  const [configured, setConfigured] = useState(false);

  const refreshBranches = useCallback(async () => {
    try {
      const res = await fetch('/api/branches', { credentials: 'include' });
      const json = await res.json() as { branches?: Record<string, unknown>[] };
      const rows = (json.branches ?? []) as Record<string, unknown>[];
      setBranches(rows.map(b => ({
        id: String(b.id ?? ''),
        name: String(b.name ?? ''),
        smtpConfigured: !!(b.smtp_host && b.smtp_user && b.smtp_pass_status),
      })));
    } catch { /* ignore */ } finally { setLoadingBranches(false); }
  }, []);

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

  const loadBranchSmtp = useCallback(async (branchId: string) => {
    setLoadingSmtp(true);
    setSmtpError(null);
    try {
      const res = await fetch(`/api/branches/${branchId}`, { credentials: 'include' });
      const json = await res.json() as { branch: Record<string, unknown> };
      const b = json.branch;
      const hasSmtp = !!(b.smtp_host && b.smtp_user && b.smtp_pass_status);
      setConfigured(hasSmtp);
      setForm({
        smtp_host: String(b.smtp_host ?? ''),
        smtp_port: String(b.smtp_port ?? '587'),
        smtp_user: String(b.smtp_user ?? ''),
        smtp_pass: '',
        smtp_from: String(b.smtp_from ?? ''),
      });
    } catch {
      setSmtpError(t('smtp.errors.loadBranch', 'Failed to load branch SMTP settings'));
    } finally {
      setLoadingSmtp(false);
    }
  }, []);

  const handleBranchChange = (id: string) => {
    setSelectedBranchId(id);
    setSmtpError(null);
    setSmtpSuccess(null);
    if (id) loadBranchSmtp(id);
    else { setForm(EMPTY_SMTP); setConfigured(false); }
  };

  const handleSave = async () => {
    if (!selectedBranchId) return;
    setSaving(true);
    setSmtpError(null);
    try {
      const body: Record<string, unknown> = {
        smtp_host: form.smtp_host || null,
        smtp_port: form.smtp_port ? parseInt(form.smtp_port, 10) : null,
        smtp_user: form.smtp_user || null,
        smtp_from: form.smtp_from || null,
      };
      if (form.smtp_pass) {
        body.smtp_pass = form.smtp_pass;
      }
      const res = await fetch(`/api/branches/${selectedBranchId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const json = await res.json() as { error?: string };
        throw new Error(json.error || t('common.saveFailed', 'Save failed'));
      }
      const isConfigured = !!(form.smtp_host && form.smtp_user && (form.smtp_pass || configured));
      setConfigured(isConfigured);
      setForm(f => ({ ...f, smtp_pass: '' }));
      setBranches(prev => prev.map(b => b.id === selectedBranchId ? { ...b, smtpConfigured: isConfigured } : b));
      setSmtpSuccess(t('smtp.success.saved', 'SMTP settings saved'));
      setTimeout(() => setSmtpSuccess(null), 3000);
    } catch (err) {
      setSmtpError(err instanceof Error ? err.message : t('common.failedToSave', 'Failed to save'));
    } finally {
      setSaving(false);
    }
  };

  const handleClear = async () => {
    if (!selectedBranchId) return;
    setClearing(true);
    setSmtpError(null);
    try {
      const res = await fetch(`/api/branches/${selectedBranchId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ smtp_host: null, smtp_port: null, smtp_user: null, smtp_pass: null, smtp_from: null }),
      });
      if (!res.ok) {
        const json = await res.json() as { error?: string };
        throw new Error(json.error || t('smtp.errors.clearFailed', 'Clear failed'));
      }
      setForm(EMPTY_SMTP);
      setConfigured(false);
      setBranches(prev => prev.map(b => b.id === selectedBranchId ? { ...b, smtpConfigured: false } : b));
      setSmtpSuccess('SMTP settings cleared');
      setTimeout(() => setSmtpSuccess(null), 3000);
    } catch (err) {
      setSmtpError(err instanceof Error ? err.message : t('smtp.errors.failedToClear', 'Failed to clear'));
    } finally {
      setClearing(false);
    }
  };

  return (
    <div className="rounded-lg p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
      <div className="flex items-center gap-3 mb-4">
        <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          <Mail size={18} style={{ color: configured ? '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))' }}>{t('smtp.label', 'Email (SMTP)')}</span>
            {selectedBranchId && (
              <span
                className="px-2 py-0.5 rounded-full text-xs font-medium"
                style={configured
                  ? { backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(142, 72%, 29%)' }
                  : { backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}
              >
                {configured ? t('common.configured', 'Configured') : t('common.notSet', 'Not set')}
              </span>
            )}
          </div>
          <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('smtp.description', 'Configure outbound SMTP per branch for order & booking confirmation emails.')}
          </p>
        </div>
      </div>

      {smtpError && (
        <div className="flex items-center gap-2 p-3 rounded-lg text-sm mb-3" style={{ backgroundColor: 'hsl(0, 84%, 95%)', color: 'hsl(0, 84%, 40%)' }}>
          <AlertCircle size={14} />{smtpError}
        </div>
      )}
      {smtpSuccess && (
        <div className="flex items-center gap-2 p-3 rounded-lg text-sm mb-3" style={{ backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(142, 72%, 29%)' }}>
          <Check size={14} />{smtpSuccess}
        </div>
      )}

      <div className="relative mb-4">
        <select
          value={selectedBranchId}
          onChange={e => handleBranchChange(e.target.value)}
          disabled={loadingBranches}
          className="w-full px-3 py-2 pr-8 text-sm rounded-lg border outline-none appearance-none"
          style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
        >
          <option value="">{loadingBranches ? t('smtp.loadingBranches', 'Loading branches…') : t('smtp.selectBranch', '— Select a branch —')}</option>
          {branches.map(b => (
            <option key={b.id} value={b.id}>{b.name}{b.smtpConfigured ? ' ✓' : ''}</option>
          ))}
        </select>
        <ChevronDown size={14} className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none" style={{ color: 'hsl(var(--muted-foreground))' }} />
      </div>

      {selectedBranchId && (
        loadingSmtp ? (
          <div className="flex items-center gap-2 py-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <Loader2 size={14} className="animate-spin" />{t('common.loading', 'Loading…')}
          </div>
        ) : (
          <div className="space-y-3">
            <div className="grid grid-cols-3 gap-2">
              <div className="col-span-2 flex flex-col gap-1">
                <label className="text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('smtp.fields.host', 'SMTP Host')}</label>
                <input
                  type="text"
                  value={form.smtp_host}
                  onChange={e => setForm(f => ({ ...f, smtp_host: e.target.value }))}
                  placeholder="smtp.example.com"
                  className="px-3 py-2 text-sm rounded-lg border outline-none"
                  style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                />
              </div>
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('smtp.fields.port', 'Port')}</label>
                <input
                  type="number"
                  value={form.smtp_port}
                  onChange={e => setForm(f => ({ ...f, smtp_port: e.target.value }))}
                  placeholder="587"
                  className="px-3 py-2 text-sm rounded-lg border outline-none"
                  style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                />
              </div>
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('smtp.fields.username', 'Username')}</label>
              <input
                type="text"
                value={form.smtp_user}
                onChange={e => setForm(f => ({ ...f, smtp_user: e.target.value }))}
                placeholder="user@example.com"
                className="px-3 py-2 text-sm rounded-lg border outline-none"
                style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
              />
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('smtp.fields.password', 'Password')}</label>
              <div className="relative">
                <input
                  type={showPass ? 'text' : 'password'}
                  value={form.smtp_pass}
                  onChange={e => setForm(f => ({ ...f, smtp_pass: e.target.value }))}
                  placeholder={configured ? t('smtp.fields.passwordKeep', 'Leave blank to keep existing password') : t('smtp.fields.passwordPlaceholder', 'SMTP password or app password')}
                  className="w-full px-3 py-2 pr-10 text-sm rounded-lg border outline-none"
                  style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                />
                <button type="button" onClick={() => setShowPass(v => !v)} className="absolute right-2 top-1/2 -translate-y-1/2 p-1">
                  {showPass ? <EyeOff size={14} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <Eye size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                </button>
              </div>
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('smtp.fields.fromAddress', 'From Address')}</label>
              <input
                type="email"
                value={form.smtp_from}
                onChange={e => setForm(f => ({ ...f, smtp_from: e.target.value }))}
                {...{placeholder: t('smtp.fields.fromPlaceholder', 'noreply@example.com (optional, defaults to username)')}}
                className="px-3 py-2 text-sm rounded-lg border outline-none"
                style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}
              />
            </div>
            <div className="flex items-center gap-2 pt-1">
              <button
                onClick={handleSave}
                disabled={saving || clearing}
                className="px-4 py-2 rounded-lg text-sm font-medium text-white transition-colors disabled:opacity-50"
                style={{ backgroundColor: 'hsl(var(--primary))' }}
              >
                {saving ? <Loader2 className="animate-spin" size={14} /> : t('common.save', 'Save')}
              </button>
              {configured && (
                <button
                  onClick={handleClear}
                  disabled={saving || clearing}
                  className="px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                  style={{ color: 'hsl(0, 84%, 50%)', border: '1px solid hsl(0, 84%, 80%)' }}
                >
                  {clearing ? <Loader2 className="animate-spin" size={14} /> : t('smtp.actions.clear', 'Clear')}
                </button>
              )}
            </div>
          </div>
        )
      )}
    </div>
  );
}

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 className="mt-6 pt-6" style={{ borderTop: '1px solid hsl(var(--border))' }}>
        <h3 className="text-sm font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('smtp.label', 'Email (SMTP)')}</h3>
        <SmtpSection />
      </div>
    </div>
  );
}
