'use client';

import React, { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { formatCoins } from '../../../lib/coins';
import { apiRequest, getCurrentUser, idempotencyKey } from '../../../lib/api';
import { loginHref } from '../../../lib/authRedirect';
import { Button } from '../../../components/Button';
import { Badge } from '../../../components/Badge';
import { PageHeader } from '../../../components/PageHeader';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

export default function MembershipPage() {
  const router = useRouter();
  const pathname = usePathname();
  const [plans, setPlans] = useState<any[]>([]);
  const [mine, setMine] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const plansRes = await apiRequest('/membership/plans');
      setPlans(plansRes.data || []);
      if (getCurrentUser()) {
        const s = await apiRequest('/membership/my-status');
        setMine(s.data);
      }
      setError('');
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

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

  const subscribe = async (planId: string) => {
    if (!getCurrentUser()) {
      router.push(loginHref(pathname || '/membership'));
      return;
    }
    setBusy(true);
    try {
      await apiRequest(`/membership/subscribe/${planId}`, {
        method: 'POST',
        idempotencyKey: idempotencyKey('mem'),
      });
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <LoadingBlock />;

  return (
    <div className="space-y-3">
      <PageHeader
        title="Membership"
        subtitle="Unlock perks and bonus coins"
        backHref="/profile"
        backLabel="Account"
      />
      {error && <ErrorBlock message={error} onRetry={load} />}
      {mine && (
        <div className="rounded-xl border border-red-200 bg-d11-soft px-4 py-3 text-sm text-d11-ink">
          Current: {mine.planId?.name || mine.status}{' '}
          {mine.expiresAt && `· expires ${new Date(mine.expiresAt).toLocaleDateString()}`}
        </div>
      )}
      {plans.length === 0 ? (
        <EmptyBlock title="No plans published." />
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {plans.map((p) => (
            <div key={p._id} className="d11-card flex flex-col p-5">
              <div className="flex items-start justify-between gap-2">
                <h2 className="text-lg font-semibold text-d11-ink">{p.name}</h2>
                <Badge variant="emerald">{formatCoins(p.price)}</Badge>
              </div>
              <p className="mt-2 text-xs text-d11-muted">{p.description || `${p.durationDays} days`}</p>
              <ul className="mt-3 flex-1 space-y-1 text-xs text-d11-muted">
                {(p.perks || []).map((b: string, i: number) => (
                  <li key={i}>· {b}</li>
                ))}
              </ul>
              <Button className="mt-4 w-full" loading={busy} onClick={() => subscribe(p._id)}>
                Subscribe
              </Button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
