'use client';

import { useEffect, useState } from 'react';
import { Zap, CheckCircle2, Lock, Loader2, Globe, Brain } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { useI18n } from '@/lib/i18n';

const FALLBACK_PROVIDERS_FACTORY = (t: (k: string) => string) => [
  { id: "google", label: t('services.fallback.google.label'), description: t('services.fallback.google.desc'), mode: "classic" as const },
];

interface AvailableProvider {
  id: string;
  label: string;
  description: string;
  mode: "classic" | "llm";
  model?: string;
}

export default function TranslationServicesPage() {
  const { t } = useI18n();
  const FALLBACK_PROVIDERS = FALLBACK_PROVIDERS_FACTORY(t);
  const [providers, setProviders] = useState<AvailableProvider[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchProviders = async () => {
      try {
        const token = localStorage.getItem("token");
        const headers: Record<string, string> = {};
        if (token) headers["Authorization"] = `Bearer ${token}`;
        const res = await fetch(`${API_BASE}/api/v1/providers/available`, { headers });
        if (res.ok) {
          const data = await res.json();
          const list = data.providers || [];
          setProviders(list.length > 0 ? list : FALLBACK_PROVIDERS);
        } else {
          setProviders(FALLBACK_PROVIDERS);
        }
      } catch {
        setProviders(FALLBACK_PROVIDERS);
      } finally {
        setIsLoading(false);
      }
    };
    fetchProviders();
  }, [FALLBACK_PROVIDERS]);

  const classicProviders = providers.filter((p) => p.mode === "classic");
  const llmProviders = providers.filter((p) => p.mode === "llm");

  return (
    <div className="max-w-4xl mx-auto w-full p-6 lg:p-8">
      {/* ── Editorial Header ───────────────────────────────────── */}
      <div className="mb-12">
        <span className="accent-pill mb-4 block w-fit">{t('services.title')}</span>
        <h1 className="text-5xl font-black uppercase tracking-tighter mb-4 leading-none text-brand-dark dark:text-white">
          {t('services.title')}
        </h1>
        <p className="text-brand-dark/40 dark:text-white/40 font-medium">{t('services.subtitle')}</p>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center min-h-[30vh]">
          <div className="text-center space-y-4">
            <div className="animate-spin rounded-full h-8 w-8 border-4 border-brand-muted border-t-brand-accent mx-auto"></div>
            <p className="text-[9px] font-black text-brand-dark/40 dark:text-white/40 uppercase tracking-widest">{t('services.loading')}</p>
          </div>
        </div>
      ) : providers.length === 0 ? (
        <div className="editorial-card p-16 bg-white dark:bg-[#141414] border-none shadow-editorial text-center">
          <p className="text-brand-dark/40 dark:text-white/40 font-medium">{t('services.noProviders')}</p>
        </div>
      ) : (
        <div className="space-y-12">
          {/* Classic providers */}
          {classicProviders.length > 0 && (
            <section className="editorial-card p-10 lg:p-12 bg-white dark:bg-[#141414] border-none shadow-editorial">
              <div className="flex items-center gap-4 mb-8 text-brand-accent">
                <Globe size={20} />
                <h3 className="text-[11px] font-black uppercase tracking-[0.3em] text-brand-dark dark:text-white">
                  {t('services.classic')}
                </h3>
              </div>
              <div className="space-y-4">
                {classicProviders.map((p) => (
                  <div
                    key={p.id}
                    className="flex items-center justify-between p-6 bg-brand-muted dark:bg-white/5 rounded-[24px] border border-black/5 dark:border-white/10 hover:-translate-y-1 transition-all"
                  >
                    <div>
                      <p className="text-[11px] font-black uppercase tracking-tight text-brand-dark dark:text-white">{p.label}</p>
                      <p className="text-[10px] text-brand-dark/30 dark:text-white/30 font-bold uppercase tracking-widest mt-1">{p.description}</p>
                    </div>
                    <span className="flex items-center gap-2 px-4 py-2 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 rounded-full text-[9px] font-black uppercase tracking-widest">
                      <CheckCircle2 size={12} /> {t('services.available')}
                    </span>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* LLM providers */}
          {llmProviders.length > 0 && (
            <section className="editorial-card p-10 lg:p-12 bg-white dark:bg-[#141414] border-none shadow-editorial">
              <div className="flex items-center gap-4 mb-8 text-brand-accent">
                <Brain size={20} />
                <h3 className="text-[11px] font-black uppercase tracking-[0.3em] text-brand-dark dark:text-white">
                  {t('services.llmPro')}
                </h3>
              </div>
              <div className="space-y-4">
                {llmProviders.map((p) => (
                  <div
                    key={p.id}
                    className="flex items-center justify-between p-6 bg-brand-muted dark:bg-white/5 rounded-[24px] border border-black/5 dark:border-white/10 hover:-translate-y-1 transition-all"
                  >
                    <div>
                      <p className="text-[11px] font-black uppercase tracking-tight text-brand-dark dark:text-white">{p.label}</p>
                      <p className="text-[10px] text-brand-dark/30 dark:text-white/30 font-bold uppercase tracking-widest mt-1">{p.description}</p>
                      {p.model && (
                        <p className="mt-2 text-[9px] font-mono text-brand-dark/20 dark:text-white/20 uppercase tracking-widest">
                          {t('services.model')}: {p.model}
                        </p>
                      )}
                    </div>
                    <span className="flex items-center gap-2 px-4 py-2 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 rounded-full text-[9px] font-black uppercase tracking-widest">
                      <CheckCircle2 size={12} /> {t('services.available')}
                    </span>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>
      )}

      {/* Admin notice */}
      <div className="editorial-card p-10 lg:p-12 bg-amber-50 dark:bg-amber-500/5 border border-amber-200 dark:border-amber-500/20 mt-12">
        <div className="flex items-center gap-4 text-amber-600 dark:text-amber-400">
          <Lock size={20} />
          <div>
            <h3 className="text-[11px] font-black uppercase tracking-[0.3em] text-amber-800 dark:text-amber-400">
              {t('services.adminOnly.title')}
            </h3>
            <p className="text-[10px] text-amber-600/60 dark:text-amber-400/60 font-bold uppercase tracking-widest mt-2">
              {t('services.adminOnly.desc')}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
