'use client';

import { useState } from 'react';
import { Sparkles, Loader2, Check, X } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';

export type PolishKind = 'general' | 'invoice_note' | 'caption' | 'letter' | 'email' | 'ticket_reply' | 'announcement' | 'task';

type Result = { polished: string; provider: string; usedFallback: boolean; warnings: { code: string; detail?: string[] }[] };

const ERRORS: Record<string, string> = {
  AI_NOT_CONFIGURED: 'AI polish is not set up yet — add NVIDIA_API_KEY (and GROQ_API_KEY as backup) to services/api/.env.',
  AI_UNAVAILABLE: 'Both AI providers are unreachable right now. Your text was left unchanged — try again shortly.',
  TOO_MANY_REQUESTS: 'Too many polish requests — wait a moment.',
  TEXT_TOO_LONG: 'That text is too long to polish in one go (limit about 6,000 characters).',
};

/**
 * "✨ Polish" — sends the text to the API, which rewrites it in professional,
 * formal, official business language (NVIDIA first, Groq as automatic fallback).
 * The result is shown for review: nothing changes until you press Use this.
 */
export default function AiPolishButton({
  text, kind, onAccept, className = '',
}: { text: string; kind: PolishKind; onAccept: (polished: string) => void; className?: string }) {
  const { accessToken, appSecretProof } = useAuth();
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState<Result | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [tone, setTone] = useState<'formal' | 'warm' | 'firm'>('formal');

  async function run() {
    if (!accessToken || !appSecretProof || !text.trim()) return;
    setBusy(true); setError(null); setResult(null);
    try {
      setResult(await adminApiFetch('/admin/ai/polish', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ text, kind, tone }) }));
    } catch (e) {
      setError(ERRORS[(e as Error).message] || 'Could not polish that text.');
    } finally { setBusy(false); }
  }

  return (
    <div className={className}>
      <div className="flex items-center gap-2">
        <button type="button" onClick={run} disabled={busy || !text.trim()}
          className="inline-flex items-center gap-1.5 text-[11px] font-semibold border border-brand-border rounded-full px-3 py-1 bg-white transition-colors hover:bg-brand-bg disabled:opacity-50">
          {busy ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} className="text-brand-red" />}
          {busy ? 'Polishing…' : 'Polish with AI'}
        </button>
        <select value={tone} onChange={(e) => setTone(e.target.value as typeof tone)} className="text-[11px] border border-brand-border rounded-full px-2 py-1 bg-white">
          <option value="formal">Formal</option><option value="warm">Formal · warm</option><option value="firm">Firm notice</option>
        </select>
      </div>
      {error && <p className="text-[11px] text-brand-red mt-1.5">{error}</p>}
      {result && (
        <div className="mt-2 border border-brand-border rounded-xl bg-brand-bg p-3 animate-scaleIn">
          <p className="text-[10px] uppercase tracking-wide text-gray-400 mb-1">Polished version{result.usedFallback ? ' (backup provider)' : ''}</p>
          <p className="text-xs whitespace-pre-wrap text-gray-800 max-h-56 overflow-y-auto">{result.polished}</p>
          {result.warnings.some((w) => w.code === 'NUMBERS_CHANGED') && (
            <p className="text-[11px] text-amber-700 mt-2">Check the figures: {result.warnings.find((w) => w.code === 'NUMBERS_CHANGED')?.detail?.join(', ')} did not appear exactly in the polished text.</p>
          )}
          <div className="flex gap-2 mt-2">
            <button type="button" onClick={() => { onAccept(result.polished); setResult(null); }} className="inline-flex items-center gap-1 bg-brand-red text-white text-[11px] font-semibold px-3 py-1 rounded-full"><Check size={12} /> Use this</button>
            <button type="button" onClick={() => setResult(null)} className="inline-flex items-center gap-1 text-[11px] text-gray-500 px-2 py-1"><X size={12} /> Discard</button>
          </div>
        </div>
      )}
    </div>
  );
}
