'use client';

import React, { useEffect, useState } from 'react';
import { formatCoins } from '../../../lib/coins';
import { apiRequest } from '../../../lib/api';
import { Button } from '../../../components/Button';
import { Badge } from '../../../components/Badge';
import { Modal } from '../../../components/Modal';

export default function AdminMembershipPage() {
  const [plans, setPlans] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    name: '',
    code: '',
    price: 99,
    durationDays: 30,
    discountPercentOnContests: 0,
    maxTeamsAllowed: 5,
    perks: 'Extra slots',
  });

  const load = async () => {
    setLoading(true);
    try {
      const res = await apiRequest('/membership/plans');
      setPlans(res.data || []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const create = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    try {
      await apiRequest('/membership/plans', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          price: Number(form.price),
          durationDays: Number(form.durationDays),
          discountPercentOnContests: Number(form.discountPercentOnContests),
          maxTeamsAllowed: Number(form.maxTeamsAllowed),
          perks: form.perks.split(',').map((s) => s.trim()).filter(Boolean),
        }),
      });
      setOpen(false);
      load();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-white">Membership Plans</h1>
          <p className="text-xs text-zinc-400">Admin CRUD for customer membership offerings</p>
        </div>
        <Button onClick={() => setOpen(true)}>Add plan</Button>
      </div>
      {loading ? (
        <p className="text-xs text-zinc-400">Loading…</p>
      ) : (
        <div className="overflow-hidden rounded-2xl border border-zinc-800">
          <table className="w-full text-left text-sm">
            <thead className="bg-zinc-950/40 text-[11px] uppercase text-zinc-500">
              <tr>
                <th className="px-4 py-3">Plan</th>
                <th className="px-4 py-3">Code</th>
                <th className="px-4 py-3">Price</th>
                <th className="px-4 py-3">Days</th>
                <th className="px-4 py-3">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-800/60">
              {plans.map((p) => (
                <tr key={p._id}>
                  <td className="px-4 py-3 text-white">{p.name}</td>
                  <td className="px-4 py-3 font-mono text-emerald-400">{p.code}</td>
                  <td className="px-4 py-3">{formatCoins(p.price)}</td>
                  <td className="px-4 py-3">{p.durationDays}</td>
                  <td className="px-4 py-3">
                    <Badge variant="emerald">{p.status}</Badge>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      <Modal isOpen={open} onClose={() => setOpen(false)} title="Create membership plan">
        <form onSubmit={create} className="space-y-3">
          {(['name', 'code'] as const).map((k) => (
            <input
              key={k}
              required
              placeholder={k}
              value={form[k]}
              onChange={(e) => setForm({ ...form, [k]: e.target.value })}
              className="w-full rounded-xl border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
            />
          ))}
          <div className="grid grid-cols-2 gap-2">
            <input
              type="number"
              value={form.price}
              onChange={(e) => setForm({ ...form, price: Number(e.target.value) })}
              className="rounded-xl border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
            />
            <input
              type="number"
              value={form.durationDays}
              onChange={(e) => setForm({ ...form, durationDays: Number(e.target.value) })}
              className="rounded-xl border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
            />
          </div>
          <input
            placeholder="Perks (comma separated)"
            value={form.perks}
            onChange={(e) => setForm({ ...form, perks: e.target.value })}
            className="w-full rounded-xl border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
          />
          <Button type="submit" loading={busy}>
            Create
          </Button>
        </form>
      </Modal>
    </div>
  );
}
