import { useState, useEffect } from 'react';
import { CopyButton } from '@/components/ui/CopyButton';
import { Button } from '@/components/ui/Button';
import { PageHeader } from '@/components/ui/PageHeader';
import { Card, CardHeader, CardTitle, CardBody } from '@/components/ui/Card';
import { Key, Download, Terminal } from 'lucide-react';

export default function Settings() {
  const [pubKey, setPubKey] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/settings/pubkey', { credentials: 'include' })
      .then(r => (r.ok ? r.text() : ''))
      .then(t => setPubKey(t))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  function downloadPubKey() {
    if (!pubKey) return;
    const blob = new Blob([pubKey], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'syncserver.pub';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <PageHeader
        title="Settings"
        description="Server configuration and SSH key management"
      />

      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="rounded-card bg-accent/10 p-1">
              <Key className="h-4 w-4 text-accent" />
            </div>
            <CardTitle>Server SSH Public Key</CardTitle>
          </div>
        </CardHeader>
        <CardBody className="space-y-4">
          <p className="text-sm text-fg-muted">
            Add this key to the{' '}
            <code className="bg-surface-raised px-1.5 py-0.5 rounded text-xs text-fg font-mono">
              ~/.ssh/authorized_keys
            </code>{' '}
            file on your remote machines to allow SyncServer to connect.
          </p>
          <div className="bg-canvas-raised rounded-card p-4 font-mono text-xs text-emerald-400/80 break-all min-h-[4rem]">
            {loading ? (
              <span className="text-fg-subtle">Loading...</span>
            ) : pubKey ? (
              pubKey
            ) : (
              <span className="text-fg-subtle">No public key available</span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <CopyButton text={pubKey} displayText="Copy public key" />
            {pubKey && (
              <Button variant="secondary" size="sm" onClick={downloadPubKey}>
                <Download className="h-3.5 w-3.5" />
                Download .pub
              </Button>
            )}
          </div>
        </CardBody>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="rounded-card bg-surface-raised p-1">
              <Terminal className="h-4 w-4 text-fg-muted" />
            </div>
            <CardTitle>Quick Reference</CardTitle>
          </div>
        </CardHeader>
        <CardBody className="space-y-4">
          <div className="space-y-3">
            <div>
              <p className="text-sm text-fg-muted mb-2">
                <span className="font-semibold text-fg">ssh-copy-id:</span> Copy
                the public key above to a remote machine:
              </p>
              <div className="bg-canvas-raised rounded-card p-3 font-mono text-xs text-fg-muted">
                cat ~/.ssh/id_ed25519.pub | ssh user@host 'cat &gt;&gt;
                ~/.ssh/authorized_keys'
              </div>
            </div>

            <div>
              <p className="text-sm text-fg-muted">
                <span className="font-semibold text-fg">Wake-on-LAN:</span>{' '}
                Make sure your target machine BIOS/UEFI has WoL enabled and is
                connected to the same network layer (L2) as this server.
              </p>
            </div>
          </div>
        </CardBody>
      </Card>
    </div>
  );
}
