"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import {
  Landmark, Smartphone, Copy, Check,
  ArrowLeft, TrendingUp, Mail, ChevronDown,
} from "lucide-react";

// ── Types ─────────────────────────────────────────────────────────────────────

type Campaign = {
  id: string;
  title: string;
  slogan: string | null;
  description: string | null;
  amountRaised: string | null;
  mediaType: string;
  imageUrl: string | null;
  videoUrl: string | null;
};

type BankProfile = {
  id: string;
  holderName: string;
  bankName: string | null;
  accountNumber: string | null;
  iban: string | null;
  bic: string | null;
  currency: string;
  description: string | null;
};

type MobileProfile = {
  id: string;
  provider: string | null;
  phoneNumber: string | null;
  holderName: string;
  description: string | null;
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function toEmbedUrl(url: string): string {
  try {
    const yt = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]{11})/);
    if (yt) return `https://www.youtube.com/embed/${yt[1]}`;
    const vimeo = url.match(/vimeo\.com\/(\d+)/);
    if (vimeo) return `https://player.vimeo.com/video/${vimeo[1]}`;
  } catch { /* ignore */ }
  return url;
}

const PROVIDER_COLORS: Record<string, string> = {
  Bankily:        "bg-green-100 text-green-800 border-green-200",
  Masrivi:        "bg-blue-100 text-blue-800 border-blue-200",
  Sedad:          "bg-purple-100 text-purple-800 border-purple-200",
  "Orange Money": "bg-orange-100 text-orange-800 border-orange-200",
  Chinguitel:     "bg-yellow-100 text-yellow-800 border-yellow-200",
  Autre:          "bg-gray-100 text-gray-800 border-gray-200",
};

// ── Sub-components ────────────────────────────────────────────────────────────

function CopyButton({ value }: { value: string }) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      onClick={() => {
        navigator.clipboard.writeText(value);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }}
      className="ml-2 p-1.5 rounded-md hover:bg-gray-200 text-gray-400 hover:text-gray-700 transition-colors flex-shrink-0"
      title="Copier"
    >
      {copied ? <Check size={13} className="text-green-600" /> : <Copy size={13} />}
    </button>
  );
}

function DetailRow({ label, value, mono }: { label: string; value: string | null; mono?: boolean }) {
  if (!value) return null;
  return (
    <div className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg gap-2">
      <span className="text-[11px] font-semibold text-gray-400 uppercase tracking-wide flex-shrink-0 min-w-[5rem]">
        {label}
      </span>
      <span className={`text-sm text-gray-800 flex-1 text-right truncate ${mono ? "font-mono" : "font-medium"}`}>
        {value}
      </span>
      <CopyButton value={value} />
    </div>
  );
}

function BankCard({ account }: { account: BankProfile }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-md transition-all duration-200 p-5 sm:p-6">
      <div className="flex items-start gap-3 mb-4">
        <div className="w-10 h-10 rounded-xl bg-[#4A7C59]/10 flex items-center justify-center flex-shrink-0">
          <Landmark size={18} className="text-[#4A7C59]" />
        </div>
        <div className="flex-1 min-w-0">
          <h3 className="font-bold text-gray-900 text-base leading-tight truncate">{account.bankName}</h3>
          <p className="text-sm text-gray-500 mt-0.5 truncate">{account.holderName}</p>
        </div>
        <span className="text-xs font-bold text-gray-400 bg-gray-100 px-2 py-1 rounded-lg flex-shrink-0">
          {account.currency}
        </span>
      </div>
      <div className="space-y-1.5">
        <DetailRow label="N° compte" value={account.accountNumber} />
        {account.iban && <DetailRow label="IBAN" value={account.iban} mono />}
        {account.bic  && <DetailRow label="BIC"  value={account.bic}  mono />}
      </div>
      {account.description && (
        <p className="mt-4 text-sm text-gray-500 border-t border-gray-100 pt-3 leading-relaxed">
          {account.description}
        </p>
      )}
    </div>
  );
}

function WalletCard({ wallet }: { wallet: MobileProfile }) {
  const provider = wallet.provider ?? "Autre";
  const colorClass = PROVIDER_COLORS[provider] ?? PROVIDER_COLORS["Autre"];
  return (
    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-md transition-all duration-200 p-5 sm:p-6">
      <div className="flex items-start gap-3 mb-4">
        <div className="w-10 h-10 rounded-xl bg-orange-50 flex items-center justify-center flex-shrink-0">
          <Smartphone size={18} className="text-orange-500" />
        </div>
        <div className="flex-1 min-w-0">
          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold border ${colorClass}`}>
            {provider}
          </span>
          <p className="text-sm text-gray-500 mt-1.5 truncate">{wallet.holderName}</p>
        </div>
      </div>
      <div className="space-y-1.5">
        <DetailRow label="Numéro" value={wallet.phoneNumber} mono />
      </div>
      {wallet.description && (
        <p className="mt-4 text-sm text-gray-500 border-t border-gray-100 pt-3 leading-relaxed">
          {wallet.description}
        </p>
      )}
    </div>
  );
}

// ── Page ─────────────────────────────────────────────────────────────────────

export default function CampaignDetailPage() {
  const { id } = useParams<{ id: string }>();

  const [campaign, setCampaign]       = useState<Campaign | null>(null);
  const [bankAccounts, setBankAccounts] = useState<BankProfile[]>([]);
  const [mobileWallets, setMobileWallets] = useState<MobileProfile[]>([]);
  const [loading, setLoading]         = useState(true);
  const [notFound, setNotFound]       = useState(false);

  useEffect(() => {
    Promise.all([
      fetch(`/api/campaign/${id}`).then((r) => r.json()),
      fetch("/api/support").then((r) => r.json()),
    ])
      .then(([campaignData, supportData]) => {
        if (!campaignData) {
          setNotFound(true);
        } else {
          setCampaign(campaignData);
          setBankAccounts(supportData.bankAccounts ?? []);
          setMobileWallets(supportData.mobileWallets ?? []);
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [id]);

  return (
    <div className="min-h-screen bg-white">

      {/* ── Loading ─────────────────────────────────────────────────────── */}
      {loading && (
        <div className="flex flex-col items-center justify-center py-40 gap-4">
          <div className="w-10 h-10 border-4 border-[#4A7C59]/20 border-t-[#4A7C59] rounded-full animate-spin" />
          <p className="text-sm text-gray-400">Chargement de la campagne…</p>
        </div>
      )}

      {/* ── Not found ───────────────────────────────────────────────────── */}
      {!loading && (notFound || !campaign) && (
        <div className="flex flex-col items-center justify-center gap-5 py-40 px-4 text-center">
          <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center">
            <Landmark size={28} className="text-gray-300" />
          </div>
          <p className="text-gray-500 text-lg font-medium">Campagne introuvable</p>
          <a
            href="/"
            className="inline-flex items-center gap-1.5 text-sm text-[#4A7C59] hover:underline font-medium"
          >
            <ArrowLeft size={15} />
            Retour à l&apos;accueil
          </a>
        </div>
      )}

      {/* ── Content ─────────────────────────────────────────────────────── */}
      {!loading && campaign && (
        <>
          {/* Hero */}
          <section className="relative bg-[#0E1A10] overflow-hidden">
            {/* Radial glow */}
            <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_70%_-10%,_rgba(74,124,89,0.2),_transparent)]" />

            <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-10 lg:py-14">
              {/* Back link */}
              <a
                href="/"
                className="inline-flex items-center gap-1.5 text-[#6DBF87] hover:text-white text-sm font-medium mb-6 sm:mb-8 transition-colors"
              >
                <ArrowLeft size={15} />
                Retour à l&apos;accueil
              </a>

              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8 lg:gap-14 items-center">

                {/* Media — first on mobile, second on desktop */}
                <div className="order-1 lg:order-2 rounded-2xl overflow-hidden aspect-video bg-[#1a2e1c] ring-1 ring-white/10 shadow-2xl">
                  {campaign.mediaType === "video" && campaign.videoUrl ? (
                    campaign.videoUrl.includes("res.cloudinary.com") ? (
                      <video
                        src={campaign.videoUrl}
                        controls
                        className="w-full h-full object-contain"
                      />
                    ) : (
                      <iframe
                        src={toEmbedUrl(campaign.videoUrl)}
                        title={campaign.title}
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowFullScreen
                        className="w-full h-full"
                      />
                    )
                  ) : campaign.imageUrl ? (
                    /* eslint-disable-next-line @next/next/no-img-element */
                    <img
                      src={campaign.imageUrl}
                      alt={campaign.title}
                      className="w-full h-full object-cover"
                    />
                  ) : null}
                </div>

                {/* Text — second on mobile, first on desktop */}
                <div className="order-2 lg:order-1 space-y-4 sm:space-y-5">
                  <span className="inline-flex items-center gap-2 bg-[#E67E22]/15 text-[#E67E22] text-xs font-bold uppercase tracking-widest px-3 py-1.5 rounded-full border border-[#E67E22]/20">
                    <span className="w-1.5 h-1.5 rounded-full bg-[#E67E22] animate-pulse inline-block" />
                    Campagne en cours
                  </span>

                  <h1 className="font-serif text-2xl sm:text-4xl lg:text-5xl font-black text-white leading-tight">
                    {campaign.title}
                  </h1>

                  {campaign.slogan && (
                    <p className="text-[#6DBF87] text-base sm:text-lg font-medium leading-snug">
                      {campaign.slogan}
                    </p>
                  )}

                  {campaign.description && (
                    <p className="text-gray-400 text-sm sm:text-base leading-relaxed">
                      {campaign.description}
                    </p>
                  )}

                  {/* Amount raised */}
                  {campaign.amountRaised && (
                    <div className="flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl px-4 py-3 w-fit">
                      <div className="w-9 h-9 rounded-lg bg-[#E67E22]/15 flex items-center justify-center flex-shrink-0">
                        <TrendingUp size={17} className="text-[#E67E22]" />
                      </div>
                      <div>
                        <p className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">
                          Montant collecté
                        </p>
                        <p className="text-xl sm:text-2xl font-black text-white leading-tight">
                          {campaign.amountRaised}
                        </p>
                      </div>
                    </div>
                  )}

                  {/* Scroll hint on mobile */}
                  <a
                    href="#soutenir"
                    className="flex sm:hidden items-center gap-1.5 text-gray-500 text-xs mt-1"
                  >
                    <ChevronDown size={14} />
                    Voir comment soutenir
                  </a>
                </div>

              </div>
            </div>
          </section>

          {/* Donation section */}
          <section id="soutenir" className="py-12 sm:py-16 bg-gradient-to-b from-gray-50 to-white">
            <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">

              {/* Section header */}
              <div className="text-center mb-10 sm:mb-14">
                <span className="inline-block text-xs font-bold text-[#4A7C59] uppercase tracking-widest mb-3">
                  Comment soutenir
                </span>
                <h2 className="text-2xl sm:text-3xl lg:text-4xl font-extrabold text-gray-900 leading-tight">
                  Contribuez à cette campagne
                </h2>
                <p className="mt-3 text-gray-500 text-sm sm:text-base max-w-md mx-auto">
                  Choisissez le mode de paiement qui vous convient le mieux.
                </p>
              </div>

              {/* Bank accounts */}
              {bankAccounts.length > 0 && (
                <div className="mb-10 sm:mb-12">
                  <div className="flex items-center gap-3 mb-5 sm:mb-6">
                    <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-[#4A7C59] flex items-center justify-center flex-shrink-0">
                      <Landmark size={18} className="text-white" />
                    </div>
                    <div>
                      <h3 className="text-lg sm:text-xl font-bold text-gray-900">Virements bancaires</h3>
                      <p className="text-xs sm:text-sm text-gray-500">Effectuez un virement depuis votre banque</p>
                    </div>
                  </div>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-5">
                    {bankAccounts.map((account) => (
                      <BankCard key={account.id} account={account} />
                    ))}
                  </div>
                </div>
              )}

              {/* Mobile wallets */}
              {mobileWallets.length > 0 && (
                <div className="mb-10 sm:mb-12">
                  <div className="flex items-center gap-3 mb-5 sm:mb-6">
                    <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-orange-500 flex items-center justify-center flex-shrink-0">
                      <Smartphone size={18} className="text-white" />
                    </div>
                    <div>
                      <h3 className="text-lg sm:text-xl font-bold text-gray-900">Paiements mobiles</h3>
                      <p className="text-xs sm:text-sm text-gray-500">Envoyez via votre portefeuille mobile</p>
                    </div>
                  </div>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-5">
                    {mobileWallets.map((wallet) => (
                      <WalletCard key={wallet.id} wallet={wallet} />
                    ))}
                  </div>
                </div>
              )}

              {bankAccounts.length === 0 && mobileWallets.length === 0 && (
                <div className="text-center py-12">
                  <div className="w-14 h-14 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4">
                    <Landmark size={24} className="text-gray-300" />
                  </div>
                  <p className="text-gray-400 text-sm">
                    Les informations de donation seront disponibles prochainement.
                  </p>
                </div>
              )}

              {/* Contact CTA */}
              <div className="bg-gradient-to-br from-[#4A7C59] to-[#3d6849] rounded-2xl p-6 sm:p-8 text-center text-white mt-4">
                <h3 className="text-lg sm:text-xl font-bold mb-2">Une question ?</h3>
                <p className="text-white/70 text-sm mb-5 max-w-sm mx-auto leading-relaxed">
                  Notre équipe est disponible pour vous accompagner et vous fournir tout document nécessaire.
                </p>
                <a
                  href="mailto:anedong94@gmail.com"
                  className="inline-flex items-center gap-2 bg-white text-[#4A7C59] px-5 sm:px-6 py-3 rounded-xl font-semibold hover:bg-gray-50 transition-colors text-sm"
                >
                  <Mail size={15} />
                  anedong94@gmail.com
                </a>
              </div>

            </div>
          </section>
        </>
      )}
    </div>
  );
}
