/**
 * PGP settings — import private key, view contact public keys.
 */

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';
import { EmptyState } from '@/components/ui/EmptyState';
import { useToast } from '@/components/ui/Toast';

import { Loader2 } from 'lucide-react';
import {
  importPgpKey,
  fetchPgpKeys,
  fetchContactPgpKeys,
  storeContactPgpKey,
  type PgpKey,
  type ContactPgpKey,
} from '@/api/mail';

export function PgpSettings() {
  const { t } = useTranslation();
  const toast = useToast();
  const [keys, setKeys] = useState<PgpKey[]>([]);
  const [contactKeys, setContactKeys] = useState<ContactPgpKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [privateKey, setPrivateKey] = useState('');
  const [passphrase, setPassphrase] = useState('');
  const [importing, setImporting] = useState(false);
  const [contactId, setContactId] = useState('');
  const [contactPublicKey, setContactPublicKey] = useState('');
  const [storingContact, setStoringContact] = useState(false);

  const load = useCallback(() => {
    setLoading(true);
    Promise.all([fetchPgpKeys(), fetchContactPgpKeys()])
      .then(([k, ck]) => {
        setKeys(k);
        setContactKeys(ck);
        setError(null);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : String(err));
      })
      .finally(() => setLoading(false));
  }, []);

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

  const handleImport = useCallback(async () => {
    if (!privateKey.trim()) return;
    setImporting(true);
    try {
      const result = await importPgpKey({ private_key: privateKey, passphrase: passphrase || undefined });
      setKeys((prev) => [...prev, result]);
      toast.success(t('mail.pgpKeyImported'));
      setPrivateKey('');
      setPassphrase('');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    } finally {
      setImporting(false);
    }
  }, [privateKey, passphrase, toast, t]);

  const handleStoreContactKey = useCallback(async () => {
    if (!contactId.trim() || !contactPublicKey.trim()) return;
    setStoringContact(true);
    try {
      await storeContactPgpKey(contactId, { public_key: contactPublicKey });
      toast.success(t('mail.contactPgpStored'));
      setContactId('');
      setContactPublicKey('');
      load();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    } finally {
      setStoringContact(false);
    }
  }, [contactId, contactPublicKey, toast, t, load]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8" data-testid="pgp-settings-loading">
        <Loader2 className="animate-spin h-5 w-5 text-secondary-400" aria-hidden="true" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-danger-50 border border-danger-200 rounded-md" role="alert" data-testid="pgp-settings-error">
        <p className="text-sm text-danger-700">{error}</p>
      </div>
    );
  }

  return (
    <div className="space-y-6" data-testid="pgp-settings">
      <Card title={t('mail.pgpImportKey')}>
        <div className="space-y-3">
          <div>
            <label className="block text-sm font-medium text-secondary-700 mb-1">{t('mail.privateKey')}</label>
            <textarea
              value={privateKey}
              onChange={(e) => setPrivateKey(e.target.value)}
              className="w-full min-h-32 border border-secondary-300 rounded-md p-3 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"
              placeholder="-----BEGIN PGP PRIVATE KEY BLOCK-----"
              data-testid="pgp-private-key"
            />
          </div>
          <Input
            label={t('mail.passphrase')}
            type="password"
            value={passphrase}
            onChange={(e) => setPassphrase(e.target.value)}
            placeholder={t('mail.passphrase')}
          />
          <Button onClick={handleImport} isLoading={importing} size="sm" data-testid="pgp-import-btn">
            {t('mail.importKey')}
          </Button>
        </div>
      </Card>

      <Card title={t('mail.pgpKeys')}>
        {keys.length === 0 ? (
          <EmptyState title={t('mail.noPgpKeys')} description={t('mail.noPgpKeysDesc')} />
        ) : (
          <ul className="space-y-2" data-testid="pgp-key-list">
            {keys.map((key) => (
              <li key={key.id} className="p-3 rounded-md border border-secondary-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-secondary-900">{key.user_id}</p>
                    <p className="text-xs text-secondary-500">Key ID: {key.key_id}</p>
                    <p className="text-xs text-secondary-400">Fingerprint: {key.fingerprint}</p>
                  </div>
                  <span className="text-xs text-secondary-400">{key.is_private ? t('mail.privateKeyLabel') : t('mail.publicKey')}</span>
                </div>
              </li>
            ))}
          </ul>
        )}
      </Card>

      <Card title={t('mail.contactPgpKeys')}>
        <div className="space-y-3 mb-4">
          <Input
            label={t('mail.contactId')}
            value={contactId}
            onChange={(e) => setContactId(e.target.value)}
            placeholder="contact-uuid"
          />
          <div>
            <label className="block text-sm font-medium text-secondary-700 mb-1">{t('mail.publicKey')}</label>
            <textarea
              value={contactPublicKey}
              onChange={(e) => setContactPublicKey(e.target.value)}
              className="w-full min-h-24 border border-secondary-300 rounded-md p-3 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"
              placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----"
              data-testid="contact-public-key"
            />
          </div>
          <Button onClick={handleStoreContactKey} isLoading={storingContact} size="sm" data-testid="store-contact-key-btn">
            {t('mail.storeContactKey')}
          </Button>
        </div>
        {contactKeys.length === 0 ? (
          <EmptyState title={t('mail.noContactKeys')} description={t('mail.noContactKeysDesc')} />
        ) : (
          <ul className="space-y-2" data-testid="contact-pgp-list">
            {contactKeys.map((ck) => (
              <li key={ck.contact_id} className="p-3 rounded-md border border-secondary-200">
                <p className="text-sm font-medium text-secondary-900">{ck.contact_name}</p>
                <p className="text-xs text-secondary-500">Key ID: {ck.key_id}</p>
                <p className="text-xs text-secondary-400">Fingerprint: {ck.fingerprint}</p>
              </li>
            ))}
          </ul>
        )}
      </Card>
    </div>
  );
}
