'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, Coins, Check, Lock, Loader2 } from 'lucide-react';
import Mascot from '../Mascot';
import { bn } from '@/lib/bn';

interface SkinItem {
  id: string;
  name: string;
  price: number;
  body: string;
  stroke: string;
  owned: boolean;
}

export default function Store() {
  const router = useRouter();
  const [coins, setCoins] = useState(0);
  const [selected, setSelected] = useState('classic');
  const [skins, setSkins] = useState<SkinItem[]>([]);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  function apply(d: any) {
    setCoins(d.coins);
    setSelected(d.selected);
    setSkins(d.skins);
  }

  useEffect(() => {
    fetch('/api/store')
      .then((r) => r.json())
      .then((d) => {
        if (d.ok) apply(d);
      })
      .finally(() => setLoading(false));
  }, []);

  async function act(action: 'buy' | 'select', skinId: string) {
    setBusy(skinId);
    setError('');
    try {
      const res = await fetch('/api/store', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, skinId }),
      });
      const d = await res.json();
      if (d.ok) apply(d);
      else setError(d.error ?? 'কিছু একটা সমস্যা হয়েছে।');
    } finally {
      setBusy(null);
    }
  }

  const current = skins.find((s) => s.id === selected);

  return (
    <main className="mx-auto max-w-2xl px-4 pt-6 sm:px-6">
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.push('/app/rewards')}
          aria-label="ফিরে যাও"
          className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
        >
          <ArrowLeft className="h-5 w-5" />
        </button>
        <h1 className="font-heading text-xl font-extrabold text-ink">তারার দোকান</h1>
        <span className="ml-auto flex items-center gap-1 rounded-full bg-leaf-100 px-3 py-1.5 text-sm font-bold text-leaf-600">
          <Coins className="h-4 w-4" /> {bn(coins)}
        </span>
      </div>

      {/* current mascot preview */}
      <div className="mt-4 flex flex-col items-center rounded-3xl bg-white p-6 shadow-card">
        <Mascot mood="happy" size={110} skin={current ? { body: current.body, stroke: current.stroke } : undefined} />
        <p className="mt-2 font-heading text-lg font-bold text-ink">{current?.name ?? 'তারা'}</p>
        <p className="text-xs text-ink-soft">কয়েন জমিয়ে নতুন তারা কিনো!</p>
      </div>

      {error && (
        <p className="mt-4 rounded-2xl bg-mango-50 px-4 py-3 text-center text-sm font-medium text-mango-700">
          {error}
        </p>
      )}

      {loading ? (
        <div className="mt-8 flex justify-center">
          <Loader2 className="h-8 w-8 animate-spin text-ink-faint" />
        </div>
      ) : (
        <div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-3">
          {skins.map((s, i) => {
            const isSelected = s.id === selected;
            return (
              <motion.div
                key={s.id}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: i * 0.05 }}
                className={`flex flex-col items-center gap-2 rounded-3xl p-4 text-center shadow-card ${
                  isSelected ? 'bg-sun-50 ring-2 ring-sun-500' : 'bg-white'
                }`}
              >
                <Mascot mood="idle" size={56} skin={{ body: s.body, stroke: s.stroke }} />
                <p className="text-sm font-bold text-ink">{s.name}</p>

                {isSelected ? (
                  <span className="flex items-center gap-1 rounded-full bg-sun-500 px-3 py-1 text-xs font-bold text-white">
                    <Check className="h-3.5 w-3.5" /> ব্যবহার হচ্ছে
                  </span>
                ) : s.owned ? (
                  <button
                    onClick={() => act('select', s.id)}
                    disabled={busy === s.id}
                    className="rounded-full bg-leaf-500 px-3 py-1 text-xs font-bold text-white transition active:scale-95"
                  >
                    {busy === s.id ? '…' : 'বেছে নাও'}
                  </button>
                ) : (
                  <button
                    onClick={() => act('buy', s.id)}
                    disabled={busy === s.id || coins < s.price}
                    className="flex items-center gap-1 rounded-full bg-mango-500 px-3 py-1 text-xs font-bold text-white transition active:scale-95 disabled:opacity-50"
                  >
                    {busy === s.id ? (
                      '…'
                    ) : coins < s.price ? (
                      <>
                        <Lock className="h-3 w-3" /> {bn(s.price)}
                      </>
                    ) : (
                      <>
                        <Coins className="h-3 w-3" /> {bn(s.price)}
                      </>
                    )}
                  </button>
                )}
              </motion.div>
            );
          })}
        </div>
      )}
    </main>
  );
}
