'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';
import { PageHeader } from '@/components/layout/page-header';

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 || []).filter((p: AvailableProvider) => p.id !== "deepl");
          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 ───────────────────────────────────── */}
      <PageHeader
        pill={t('services.pill')}
        titleBase={t('services.title')}
        titleAccent={t('services.titleAccent')}
        subtitle={t('services.subtitle')}
        className="mb-12"
      />

      {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-xs font-bold text-brand-dark/50 dark:text-white/50 uppercase tracking-wider" role="status">{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/50 dark:text-white/50 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-xs font-black uppercase tracking-[0.2em] 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-[11px] text-brand-dark/50 dark:text-white/50 font-semibold uppercase tracking-wider 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-[10px] font-black uppercase tracking-wider">
                      <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-xs font-black uppercase tracking-[0.2em] 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-[11px] text-brand-dark/50 dark:text-white/50 font-semibold uppercase tracking-wider mt-1">{p.description}</p>
                      {p.model && (
                        <p className="mt-2 text-[10px] font-mono text-brand-dark/40 dark:text-white/40 uppercase tracking-wider">
                          {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-[10px] font-black uppercase tracking-wider">
                      <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-xs font-black uppercase tracking-[0.2em] text-amber-800 dark:text-amber-400">
              {t('services.adminOnly.title')}
            </h3>
            <p className="text-[11px] text-amber-600/80 dark:text-amber-400/80 font-semibold uppercase tracking-wider mt-2">
              {t('services.adminOnly.desc')}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
