'use client';

import { useEffect, useState } from 'react';
import { CheckCircle, XCircle, RefreshCw, Eye, EyeOff, Trash2, FileText } from 'lucide-react';

interface FicConfig {
  configured: boolean;
  clientId: string;
  clientSecretMasked: string;
  companyId: string;
  vatId: string;
  hasAccessToken: boolean;
  accessTokenMasked: string;
  hasRefreshToken: boolean;
  expiresAt: string | null;
  updatedAt: string | null;
}

interface TestResult {
  ok: boolean;
  companyName?: string;
  error?: string;
}

interface TestInvoiceResult {
  ok: boolean;
  docId?: number;
  error?: string;
}

export default function AdminFattureInCloud() {
  const [config, setConfig] = useState<FicConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<TestResult | null>(null);
  const [sendingTestInvoice, setSendingTestInvoice] = useState(false);
  const [testInvoiceResult, setTestInvoiceResult] = useState<TestInvoiceResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [showSecret, setShowSecret] = useState(false);
  const [showAccessToken, setShowAccessToken] = useState(false);
  const [showRefreshToken, setShowRefreshToken] = useState(false);

  const [form, setForm] = useState({
    clientId: '',
    clientSecret: '',
    companyId: '',
    vatId: '0',
    accessToken: '',
    refreshToken: '',
  });

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

  const load = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch('/api/admin/fatture-in-cloud', { credentials: 'include' });
      if (!res.ok) {
        if (res.status === 403) { setError('Admin access required.'); return; }
        throw new Error('Failed to load configuration');
      }
      const data = await res.json() as FicConfig;
      setConfig(data);
      setForm(f => ({
        ...f,
        clientId: data.clientId,
        companyId: data.companyId,
        vatId: data.vatId || '0',
      }));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSuccess(null);
    setTestResult(null);
    try {
      const res = await fetch('/api/admin/fatture-in-cloud', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clientId: form.clientId.trim(),
          clientSecret: form.clientSecret.trim() || undefined,
          companyId: form.companyId.trim(),
          vatId: form.vatId.trim(),
          accessToken: form.accessToken.trim() || undefined,
          refreshToken: form.refreshToken.trim() || undefined,
        }),
      });
      if (!res.ok) throw new Error((await res.json() as { error: string }).error ?? 'Save failed');
      setSuccess('Settings saved.');
      setForm(f => ({ ...f, clientSecret: '', accessToken: '', refreshToken: '' }));
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  const handleTest = async () => {
    setTesting(true);
    setTestResult(null);
    setError(null);
    try {
      const res = await fetch('/api/admin/fatture-in-cloud?test=1', { credentials: 'include' });
      const data = await res.json() as TestResult;
      setTestResult(data);
    } catch (err) {
      setTestResult({ ok: false, error: err instanceof Error ? err.message : 'Test failed' });
    } finally {
      setTesting(false);
    }
  };

  const handleClearTokens = async () => {
    if (!confirm('Clear stored access and refresh tokens? You will need to paste new ones.')) return;
    await fetch('/api/admin/fatture-in-cloud', { method: 'DELETE', credentials: 'include' });
    setSuccess('Tokens cleared.');
    await load();
  };

  const handleSendTestInvoice = async () => {
    setSendingTestInvoice(true);
    setTestInvoiceResult(null);
    setError(null);
    try {
      const res = await fetch('/api/admin/fatture-in-cloud/test-invoice', {
        method: 'POST',
        credentials: 'include',
      });
      const data = await res.json() as TestInvoiceResult;
      setTestInvoiceResult(data);
    } catch (err) {
      setTestInvoiceResult({ ok: false, error: err instanceof Error ? err.message : 'Request failed' });
    } finally {
      setSendingTestInvoice(false);
    }
  };

  const field = (id: string) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm(f => ({ ...f, [id]: e.target.value }));

  const tokenExpiry = config?.expiresAt
    ? new Date(config.expiresAt)
    : null;
  const tokenExpired = tokenExpiry ? tokenExpiry < new Date() : false;

  if (loading) {
    return (
      <div className="flex min-h-[20rem] items-center justify-center">
        <p className="text-sm text-muted">Loading…</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">

      {/* Header */}
      <div className="glass rounded-xl p-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h2 className="text-2xl font-bold text-foreground">Fatture in Cloud</h2>
            <p className="mt-1 text-sm text-muted">
              Configure the FIC integration used to automatically issue invoices after each successful charge.
            </p>
          </div>
          <ConnectionBadge configured={!!config?.configured} hasToken={!!config?.hasAccessToken} expired={tokenExpired} />
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</div>
      )}
      {success && (
        <div className="rounded-lg border border-green-200 bg-green-50 p-4 text-sm text-green-700">{success}</div>
      )}

      <form onSubmit={handleSave} className="space-y-6">

        {/* OAuth App Credentials */}
        <div className="glass rounded-xl p-6 space-y-5">
          <h3 className="text-sm font-semibold uppercase tracking-wider text-muted">OAuth App Credentials</h3>
          <p className="text-xs text-muted">
            Create an app at <span className="font-mono text-foreground">developers.fattureincloud.it</span> and paste the credentials here.
          </p>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">Client ID</label>
              <input
                type="text"
                value={form.clientId}
                onChange={field('clientId')}
                placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 text-sm text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
              />
            </div>

            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">Client Secret</label>
              <div className="relative">
                <input
                  type={showSecret ? 'text' : 'password'}
                  value={form.clientSecret}
                  onChange={field('clientSecret')}
                  placeholder={config?.clientSecretMasked || 'paste new secret to update'}
                  className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 pr-9 text-sm text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
                />
                <button type="button" onClick={() => setShowSecret(s => !s)}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted hover:text-foreground">
                  {showSecret ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">Company ID</label>
              <input
                type="text"
                value={form.companyId}
                onChange={field('companyId')}
                placeholder="12345678"
                className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 text-sm text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
              />
              <p className="text-[11px] text-muted">Found in your FIC company URL.</p>
            </div>

            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">VAT Type ID</label>
              <input
                type="text"
                value={form.vatId}
                onChange={field('vatId')}
                placeholder="0"
                className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 text-sm text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
              />
              <p className="text-[11px] text-muted">FIC internal VAT type id. 0 = exempt.</p>
            </div>
          </div>
        </div>

        {/* Tokens */}
        <div className="glass rounded-xl p-6 space-y-5">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted">OAuth Tokens</h3>
            {(config?.hasAccessToken || config?.hasRefreshToken) && (
              <button type="button" onClick={handleClearTokens}
                className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-red-500 hover:bg-red-500/10 border border-red-200/30 transition">
                <Trash2 className="w-3.5 h-3.5" /> Clear tokens
              </button>
            )}
          </div>

          {tokenExpiry && (
            <div className={`rounded-lg border px-4 py-3 text-xs flex items-center gap-2 ${
              tokenExpired
                ? 'border-red-200 bg-red-50 text-red-700'
                : 'border-green-200 bg-green-50 text-green-700'
            }`}>
              {tokenExpired
                ? <XCircle className="w-4 h-4 shrink-0" />
                : <CheckCircle className="w-4 h-4 shrink-0" />}
              Access token {tokenExpired ? 'expired' : 'valid until'}{' '}
              {tokenExpiry.toLocaleString()}
            </div>
          )}

          <p className="text-xs text-muted">
            Two options: <strong className="text-foreground">Manual token</strong> (from FIC Settings → Connected Applications — never expires, no refresh token needed) or <strong className="text-foreground">OAuth token</strong> (24h expiry, paste both tokens and the system auto-refreshes).
          </p>

          <div className="space-y-4">
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">Access Token</label>
              <div className="relative">
                <input
                  type={showAccessToken ? 'text' : 'password'}
                  value={form.accessToken}
                  onChange={field('accessToken')}
                  placeholder={config?.accessTokenMasked || 'paste access token'}
                  className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 pr-9 text-sm font-mono text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
                />
                <button type="button" onClick={() => setShowAccessToken(s => !s)}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted hover:text-foreground">
                  {showAccessToken ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted uppercase tracking-wide">Refresh Token</label>
              <div className="relative">
                <input
                  type={showRefreshToken ? 'text' : 'password'}
                  value={form.refreshToken}
                  onChange={field('refreshToken')}
                  placeholder={config?.hasRefreshToken ? '••••••••••••••••' : 'paste refresh token'}
                  className="w-full rounded-lg border border-border bg-surface-light px-3 py-2 pr-9 text-sm font-mono text-foreground placeholder-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/40"
                />
                <button type="button" onClick={() => setShowRefreshToken(s => !s)}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted hover:text-foreground">
                  {showRefreshToken ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex flex-wrap items-center gap-3">
          <button
            type="submit"
            disabled={saving}
            className="rounded-lg bg-accent px-5 py-2 text-sm font-medium text-white transition hover:opacity-90 disabled:opacity-50"
          >
            {saving ? 'Saving…' : 'Save Settings'}
          </button>

          <button
            type="button"
            onClick={handleTest}
            disabled={testing || !config?.configured || !config?.hasAccessToken}
            className="flex items-center gap-2 rounded-lg border border-border px-5 py-2 text-sm font-medium text-foreground transition hover:bg-surface-light disabled:opacity-40"
          >
            <RefreshCw className={`w-4 h-4 ${testing ? 'animate-spin' : ''}`} />
            {testing ? 'Testing…' : 'Test Connection'}
          </button>

          <button
            type="button"
            onClick={handleSendTestInvoice}
            disabled={sendingTestInvoice || !config?.configured || !config?.hasAccessToken}
            className="flex items-center gap-2 rounded-lg border border-border px-5 py-2 text-sm font-medium text-foreground transition hover:bg-surface-light disabled:opacity-40"
          >
            <FileText className={`w-4 h-4 ${sendingTestInvoice ? 'animate-pulse' : ''}`} />
            {sendingTestInvoice ? 'Sending…' : 'Send Test Invoice (€1)'}
          </button>
        </div>
      </form>

      {/* Test invoice result */}
      {testInvoiceResult && (
        <div className={`rounded-xl border p-5 flex items-start gap-3 ${
          testInvoiceResult.ok
            ? 'border-green-200 bg-green-50'
            : 'border-red-200 bg-red-50'
        }`}>
          {testInvoiceResult.ok
            ? <CheckCircle className="w-5 h-5 shrink-0 text-green-600 mt-0.5" />
            : <XCircle className="w-5 h-5 shrink-0 text-red-600 mt-0.5" />}
          <div>
            {testInvoiceResult.ok ? (
              <>
                <p className="text-sm font-semibold text-green-800">Test invoice created</p>
                {testInvoiceResult.docId && (
                  <p className="text-xs text-green-700 mt-0.5">FIC document ID: <span className="font-mono">{testInvoiceResult.docId}</span></p>
                )}
                <p className="text-xs text-green-700 mt-0.5">Check your Fatture in Cloud dashboard — you can safely delete it.</p>
              </>
            ) : (
              <>
                <p className="text-sm font-semibold text-red-800">Invoice creation failed</p>
                {testInvoiceResult.error && (
                  <p className="text-xs text-red-700 mt-0.5 font-mono">{testInvoiceResult.error}</p>
                )}
              </>
            )}
          </div>
        </div>
      )}

      {/* Test connection result */}
      {testResult && (
        <div className={`rounded-xl border p-5 flex items-start gap-3 ${
          testResult.ok
            ? 'border-green-200 bg-green-50'
            : 'border-red-200 bg-red-50'
        }`}>
          {testResult.ok
            ? <CheckCircle className="w-5 h-5 shrink-0 text-green-600 mt-0.5" />
            : <XCircle className="w-5 h-5 shrink-0 text-red-600 mt-0.5" />}
          <div>
            {testResult.ok ? (
              <>
                <p className="text-sm font-semibold text-green-800">Connected</p>
                {testResult.companyName && (
                  <p className="text-xs text-green-700 mt-0.5">Company: {testResult.companyName}</p>
                )}
              </>
            ) : (
              <>
                <p className="text-sm font-semibold text-red-800">Connection failed</p>
                {testResult.error && (
                  <p className="text-xs text-red-700 mt-0.5 font-mono">{testResult.error}</p>
                )}
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function ConnectionBadge({ configured, hasToken, expired }: {
  configured: boolean;
  hasToken: boolean;
  expired: boolean;
}) {
  if (!configured) {
    return (
      <span className="inline-flex items-center gap-1.5 rounded-full border border-orange-200 bg-orange-50 px-3 py-1 text-xs font-medium text-orange-700">
        <span className="h-1.5 w-1.5 rounded-full bg-orange-500" />
        Not configured
      </span>
    );
  }
  if (!hasToken || expired) {
    return (
      <span className="inline-flex items-center gap-1.5 rounded-full border border-yellow-200 bg-yellow-50 px-3 py-1 text-xs font-medium text-yellow-700">
        <span className="h-1.5 w-1.5 rounded-full bg-yellow-500" />
        Token {expired ? 'expired' : 'missing'}
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full border border-green-200 bg-green-50 px-3 py-1 text-xs font-medium text-green-700">
      <span className="h-1.5 w-1.5 rounded-full bg-green-500" />
      Connected
    </span>
  );
}
