"use client";

import { useEffect, useState } from "react";
import { Landmark, Smartphone, Copy, Check, Mail, Phone } from "lucide-react";

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;
};

// Colour per provider
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",
};

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

function BankCard({ account }: { account: BankProfile }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-md transition-shadow p-6">
      {/* Bank name header */}
      <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={20} className="text-[#4A7C59]" />
        </div>
        <div>
          <h3 className="font-bold text-gray-900 text-lg leading-tight">{account.bankName}</h3>
          <p className="text-sm text-gray-500 mt-0.5">{account.holderName}</p>
        </div>
        <span className="ml-auto text-xs font-semibold text-gray-400 bg-gray-100 px-2 py-1 rounded-lg">
          {account.currency}
        </span>
      </div>

      {/* Account details */}
      <div className="space-y-2">
        <DetailRow label="N° de 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">
          {account.description}
        </p>
      )}
    </div>
  );
}

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-1.5 px-3 bg-gray-50 rounded-lg">
      <span className="text-xs font-medium text-gray-500 uppercase tracking-wide w-28 flex-shrink-0">{label}</span>
      <span className={`text-sm text-gray-800 flex-1 text-right ${mono ? "font-mono" : "font-medium"}`}>
        {value}
      </span>
      <CopyButton value={value} />
    </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-shadow 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={20} className="text-orange-500" />
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 flex-wrap">
            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold border ${colorClass}`}>
              {provider}
            </span>
          </div>
          <p className="text-sm text-gray-500 mt-1">{wallet.holderName}</p>
        </div>
      </div>

      <div className="space-y-2">
        <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">
          {wallet.description}
        </p>
      )}
    </div>
  );
}

export default function SoutenirPage() {
  const [bankAccounts, setBankAccounts] = useState<BankProfile[]>([]);
  const [mobileWallets, setMobileWallets] = useState<MobileProfile[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/support")
      .then((r) => r.json())
      .then((data) => {
        setBankAccounts(data.bankAccounts ?? []);
        setMobileWallets(data.mobileWallets ?? []);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <main className="min-h-screen bg-gradient-to-b from-gray-50 to-white pt-24 pb-20">

      {/* Hero */}
      <section className="max-w-4xl mx-auto px-4 sm:px-6 text-center mb-16">
        <span className="inline-flex items-center gap-2 text-[#4A7C59] font-semibold text-sm uppercase tracking-widest mb-4">
          <span className="w-8 h-px bg-[#4A7C59]" />
          Soutenir notre mission
          <span className="w-8 h-px bg-[#4A7C59]" />
        </span>
        <h1 className="text-4xl sm:text-5xl font-extrabold text-gray-900 leading-tight mb-6">
          Contribuez à la lutte contre<br />
          <span className="text-[#4A7C59]">la malnutrition en Mauritanie</span>
        </h1>
        <p className="text-lg text-gray-600 max-w-2xl mx-auto leading-relaxed">
          Votre soutien financier permet à ANED de poursuivre ses programmes
          de nutrition, de sécurité alimentaire et de développement communautaire
          au bénéfice des enfants et des familles vulnérables.
        </p>
      </section>

      {loading ? (
        <div className="flex justify-center py-16">
          <div className="w-10 h-10 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <>
          {/* Bank Accounts */}
          {bankAccounts.length > 0 && (
            <section className="max-w-6xl mx-auto px-4 sm:px-6 mb-16">
              <div className="flex items-center gap-3 mb-8">
                <div className="w-10 h-10 rounded-xl bg-[#4A7C59] flex items-center justify-center">
                  <Landmark size={20} className="text-white" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Virements bancaires</h2>
                  <p className="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-5">
                {bankAccounts.map((account) => (
                  <BankCard key={account.id} account={account} />
                ))}
              </div>
            </section>
          )}

          {/* Mobile Wallets */}
          {mobileWallets.length > 0 && (
            <section className="max-w-6xl mx-auto px-4 sm:px-6 mb-16">
              <div className="flex items-center gap-3 mb-8">
                <div className="w-10 h-10 rounded-xl bg-orange-500 flex items-center justify-center">
                  <Smartphone size={20} className="text-white" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Paiements mobiles</h2>
                  <p className="text-sm text-gray-500">Envoyez directement via votre portefeuille mobile</p>
                </div>
              </div>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {mobileWallets.map((wallet) => (
                  <WalletCard key={wallet.id} wallet={wallet} />
                ))}
              </div>
            </section>
          )}

          {/* Empty state */}
          {bankAccounts.length === 0 && mobileWallets.length === 0 && (
            <div className="max-w-md mx-auto text-center py-16 px-4">
              <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4">
                <Landmark size={28} className="text-gray-400" />
              </div>
              <p className="text-gray-500">
                Les informations de donation seront disponibles prochainement.
              </p>
            </div>
          )}
        </>
      )}

      {/* Contact CTA */}
      <section className="max-w-3xl mx-auto px-4 sm:px-6">
        <div className="bg-gradient-to-br from-[#4A7C59] to-[#3d6849] rounded-2xl p-8 text-center text-white">
          <h3 className="text-2xl font-bold mb-3">Une question sur les dons ?</h3>
          <p className="text-white/80 mb-6 max-w-lg mx-auto">
            Notre équipe est disponible pour vous accompagner et vous fournir
            un reçu fiscal ou tout autre document nécessaire.
          </p>
          <div className="flex flex-wrap items-center justify-center gap-4">
            <a
              href="mailto:anedong94@gmail.com"
              className="inline-flex items-center gap-2 bg-white text-[#4A7C59] px-6 py-3 rounded-xl font-semibold hover:bg-gray-50 transition-colors"
            >
              <Mail size={18} />
              anedong94@gmail.com
            </a>
            <a
              href="/contact"
              className="inline-flex items-center gap-2 bg-white/10 hover:bg-white/20 text-white px-6 py-3 rounded-xl font-semibold transition-colors border border-white/20"
            >
              <Phone size={18} />
              Nous contacter
            </a>
          </div>
        </div>
      </section>
    </main>
  );
}
