'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  ArrowLeft,
  Ban,
  CheckCircle2,
  KeyRound,
  MinusCircle,
  PlusCircle,
  Monitor,
  Smartphone,
} from 'lucide-react';
import { apiRequest } from '../../../../lib/api';
import { formatCoins } from '../../../../lib/coins';
import { Badge } from '../../../../components/Badge';
import { Button } from '../../../../components/Button';
import { Modal } from '../../../../components/Modal';
import { ShimmerProfile } from '../../../../components/Shimmer';

type Tab = 'overview' | 'transactions' | 'analytics' | 'devices' | 'history' | 'pnl';

function parseUa(ua: string) {
  if (!ua) return { device: 'Unknown', browser: 'Unknown', os: 'Unknown' };
  const mobile = /Mobile|Android|iPhone|iPad/i.test(ua);
  let browser = 'Browser';
  if (/Edg\//i.test(ua)) browser = 'Edge';
  else if (/Chrome\//i.test(ua)) browser = 'Chrome';
  else if (/Firefox\//i.test(ua)) browser = 'Firefox';
  else if (/Safari\//i.test(ua) && !/Chrome/i.test(ua)) browser = 'Safari';
  let os = 'Unknown OS';
  if (/Windows/i.test(ua)) os = 'Windows';
  else if (/Mac OS/i.test(ua)) os = 'macOS';
  else if (/Android/i.test(ua)) os = 'Android';
  else if (/iPhone|iPad/i.test(ua)) os = 'iOS';
  else if (/Linux/i.test(ua)) os = 'Linux';
  return { device: mobile ? 'Mobile' : 'Desktop', browser, os };
}

function coins(n: number) {
  return formatCoins(n);
}

export default function AdminPlayerProfilePage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [tab, setTab] = useState<Tab>('overview');
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState('');

  const [coinOpen, setCoinOpen] = useState(false);
  const [coinMode, setCoinMode] = useState<'deposit' | 'deduct'>('deposit');
  const [coinAmount, setCoinAmount] = useState(100);
  const [coinType, setCoinType] = useState<'deposit' | 'winning' | 'bonus'>('deposit');
  const [coinReason, setCoinReason] = useState('');

  const [pwOpen, setPwOpen] = useState(false);
  const [newPassword, setNewPassword] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const res = await apiRequest(`/users/${id}/profile`);
      setData(res.data);
    } catch (e: any) {
      setError(e.message || 'Failed to load profile');
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  const user = data?.user;
  const wallet = data?.wallet;
  const pnl = data?.pnl;
  const analytics = data?.analytics;

  const setStatus = async (status: 'ACTIVE' | 'SUSPENDED') => {
    const reason =
      status === 'SUSPENDED'
        ? window.prompt('Reason for blocking this account?') || ''
        : 'Unblocked by admin';
    if (status === 'SUSPENDED' && reason.trim().length < 3) {
      setMsg('Block reason required (min 3 chars).');
      return;
    }
    setBusy(true);
    setMsg('');
    try {
      await apiRequest(`/users/${id}/status`, {
        method: 'PATCH',
        body: JSON.stringify({ status, reason }),
      });
      setMsg(status === 'SUSPENDED' ? 'Account blocked.' : 'Account unblocked.');
      await load();
    } catch (e: any) {
      setMsg(e.message);
    } finally {
      setBusy(false);
    }
  };

  const submitCoins = async (e: React.FormEvent) => {
    e.preventDefault();
    if (coinReason.trim().length < 5) {
      setMsg('Reason must be at least 5 characters.');
      return;
    }
    setBusy(true);
    setMsg('');
    try {
      const amount = coinMode === 'deposit' ? Math.abs(coinAmount) : -Math.abs(coinAmount);
      await apiRequest('/wallet/admin/adjust', {
        method: 'POST',
        idempotencyKey: `adj-${id}-${Date.now()}`,
        body: JSON.stringify({
          userId: id,
          amount,
          balanceType: coinType,
          reason: coinReason.trim(),
        }),
      });
      setCoinOpen(false);
      setCoinReason('');
      setMsg(coinMode === 'deposit' ? 'Balance added.' : 'Balance deducted.');
      await load();
    } catch (err: any) {
      setMsg(err.message);
    } finally {
      setBusy(false);
    }
  };

  const submitPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword.length < 8) {
      setMsg('Password must be at least 8 characters.');
      return;
    }
    setBusy(true);
    setMsg('');
    try {
      await apiRequest(`/users/${id}/reset-password`, {
        method: 'POST',
        body: JSON.stringify({ newPassword }),
      });
      setPwOpen(false);
      setNewPassword('');
      setMsg('Password reset. All sessions revoked.');
    } catch (err: any) {
      setMsg(err.message);
    } finally {
      setBusy(false);
    }
  };

  const tabs: { id: Tab; label: string }[] = [
    { id: 'overview', label: 'Overview' },
    { id: 'transactions', label: 'Transactions' },
    { id: 'analytics', label: 'Analytics' },
    { id: 'devices', label: 'Devices' },
    { id: 'history', label: 'Game history' },
    { id: 'pnl', label: 'P&L' },
  ];

  if (loading) return <ShimmerProfile />;
  if (error || !user) {
    return (
      <div className="space-y-4">
        <button
          type="button"
          onClick={() => router.push('/admin/users')}
          className="inline-flex items-center gap-1.5 text-xs text-zinc-400 hover:text-white"
        >
          <ArrowLeft className="h-3.5 w-3.5" /> Back to players
        </button>
        <p className="text-sm text-rose-400">{error || 'Player not found'}</p>
      </div>
    );
  }

  const blocked = user.status === 'SUSPENDED' || user.status === 'INACTIVE';

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <button
          type="button"
          onClick={() => router.push('/admin/users')}
          className="inline-flex items-center gap-1.5 text-xs text-zinc-400 hover:text-white"
        >
          <ArrowLeft className="h-3.5 w-3.5" /> Players
        </button>
        {msg && <p className="text-xs font-medium text-emerald-400">{msg}</p>}
      </div>

      {/* Header */}
      <div className="rounded-2xl border border-zinc-800 bg-zinc-900/70 p-5">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-2xl font-bold text-white">{user.name}</h1>
              <Badge variant={user.status === 'ACTIVE' ? 'emerald' : 'rose'}>{user.status}</Badge>
              <Badge variant="slate">KYC {user.kycStatus}</Badge>
            </div>
            <p className="mt-1 font-mono text-sm text-zinc-400">{user.phone}</p>
            <p className="mt-1 text-[11px] text-zinc-500">
              Joined {new Date(user.createdAt).toLocaleString()} · {analytics?.accountAgeDays ?? 0}{' '}
              days
            </p>
            <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
              {[
                { label: 'Total', value: coins(wallet?.totalBalance) },
                { label: 'Deposit', value: coins(wallet?.depositBalance) },
                { label: 'Winnings', value: coins(wallet?.winningBalance) },
                { label: 'Bonus', value: coins(wallet?.bonusBalance) },
              ].map((s) => (
                <div key={s.label} className="rounded-xl border border-zinc-800 bg-zinc-950/60 px-3 py-2.5">
                  <div className="text-[10px] font-semibold uppercase text-zinc-500">{s.label}</div>
                  <div className="mt-0.5 font-mono text-sm font-bold text-white">{s.value}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="flex flex-wrap gap-2">
            <Button
              size="sm"
              className="gap-1.5"
              onClick={() => {
                setCoinMode('deposit');
                setCoinOpen(true);
              }}
            >
              <PlusCircle className="h-3.5 w-3.5" /> Deposit
            </Button>
            <Button
              size="sm"
              variant="secondary"
              className="gap-1.5"
              onClick={() => {
                setCoinMode('deduct');
                setCoinOpen(true);
              }}
            >
              <MinusCircle className="h-3.5 w-3.5" /> Deduct
            </Button>
            <Button size="sm" variant="amber" className="gap-1.5" onClick={() => setPwOpen(true)}>
              <KeyRound className="h-3.5 w-3.5" /> Reset password
            </Button>
            {blocked ? (
              <Button
                size="sm"
                variant="secondary"
                className="gap-1.5"
                loading={busy}
                onClick={() => setStatus('ACTIVE')}
              >
                <CheckCircle2 className="h-3.5 w-3.5" /> Unblock
              </Button>
            ) : (
              <Button
                size="sm"
                variant="danger"
                className="gap-1.5"
                loading={busy}
                onClick={() => setStatus('SUSPENDED')}
              >
                <Ban className="h-3.5 w-3.5" /> Block
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-950/50 p-1">
        {tabs.map((t) => (
          <button
            key={t.id}
            type="button"
            onClick={() => setTab(t.id)}
            className={`shrink-0 rounded-lg px-3.5 py-2 text-xs font-semibold transition ${
              tab === t.id
                ? 'bg-emerald-500/15 text-emerald-400'
                : 'text-zinc-400 hover:text-zinc-200'
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'overview' && (
        <div className="grid gap-4 lg:grid-cols-2">
          <section className="rounded-2xl border border-zinc-800 bg-zinc-900/50 p-5">
            <h2 className="text-sm font-bold text-white">Account</h2>
            <dl className="mt-3 space-y-2 text-xs">
              {[
                ['Role', user.role],
                ['Wallet status', wallet?.status],
                ['Signup bonus', user.signupBonusClaimed ? 'Claimed' : 'Not claimed'],
                ['KYC doc', data.kyc?.status || 'None'],
                ['Active sessions', data.activeSessionCount],
              ].map(([k, v]) => (
                <div key={k as string} className="flex justify-between gap-4 border-b border-zinc-800/80 py-2">
                  <dt className="text-zinc-500">{k}</dt>
                  <dd className="font-medium text-zinc-200">{String(v)}</dd>
                </div>
              ))}
            </dl>
          </section>
          <section className="rounded-2xl border border-zinc-800 bg-zinc-900/50 p-5">
            <h2 className="text-sm font-bold text-white">Quick P&amp;L</h2>
            <dl className="mt-3 space-y-2 text-xs">
              {[
                ['Net gaming', coins(pnl?.netGaming)],
                ['Cashflow', coins(pnl?.netCashflow)],
                ['Est. P&L', coins(pnl?.estimatedPnL)],
                ['Contests joined', analytics?.contestJoined],
              ].map(([k, v]) => (
                <div key={k as string} className="flex justify-between gap-4 border-b border-zinc-800/80 py-2">
                  <dt className="text-zinc-500">{k}</dt>
                  <dd className="font-mono font-medium text-zinc-200">{String(v)}</dd>
                </div>
              ))}
            </dl>
            <button
              type="button"
              onClick={() => setTab('pnl')}
              className="mt-3 text-xs font-semibold text-emerald-400 hover:underline"
            >
              Full P&amp;L breakdown →
            </button>
          </section>
        </div>
      )}

      {tab === 'transactions' && (
        <div className="overflow-hidden rounded-2xl border border-zinc-800 bg-zinc-900/50">
          {(data.transactions || []).length === 0 ? (
            <p className="p-8 text-center text-xs text-zinc-500">No transactions yet.</p>
          ) : (
            <table className="w-full text-left text-xs">
              <thead className="border-b border-zinc-800 bg-zinc-950/50 text-[10px] uppercase text-zinc-500">
                <tr>
                  <th className="px-4 py-3">When</th>
                  <th className="px-4 py-3">Type</th>
                  <th className="px-4 py-3">Amount</th>
                  <th className="px-4 py-3">Bucket</th>
                  <th className="px-4 py-3">Note</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-800/60 font-mono">
                {data.transactions.map((tx: any) => (
                  <tr key={tx._id} className="hover:bg-zinc-800/20">
                    <td className="px-4 py-2.5 text-zinc-400">
                      {new Date(tx.createdAt).toLocaleString()}
                    </td>
                    <td className="px-4 py-2.5 text-zinc-200">{tx.type}</td>
                    <td
                      className={`px-4 py-2.5 font-bold ${
                        tx.amount >= 0 ? 'text-emerald-400' : 'text-rose-400'
                      }`}
                    >
                      {tx.amount >= 0 ? '+' : ''}
                      {coins(tx.amount)}
                    </td>
                    <td className="px-4 py-2.5 text-zinc-400">{tx.balanceType}</td>
                    <td className="max-w-[220px] truncate px-4 py-2.5 font-sans text-zinc-500">
                      {tx.reason || tx.description}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {tab === 'analytics' && (
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          {[
            { label: 'Contests joined', value: analytics?.contestJoined },
            { label: 'Fantasy teams', value: analytics?.fantasyTeams },
            { label: 'Heroes entries', value: analytics?.heroEntries },
            { label: 'Prizes won', value: coins(analytics?.totalPrizesWon) },
            { label: 'Avg points', value: analytics?.avgContestPoints },
            { label: 'Account age', value: `${analytics?.accountAgeDays}d` },
            { label: 'Deposited', value: coins(pnl?.totalDeposited) },
            { label: 'Withdrawn', value: coins(pnl?.totalWithdrawn) },
          ].map((c) => (
            <div key={c.label} className="rounded-2xl border border-zinc-800 bg-zinc-900/50 p-4">
              <div className="text-[10px] font-semibold uppercase text-zinc-500">{c.label}</div>
              <div className="mt-2 text-xl font-bold text-white">{c.value}</div>
            </div>
          ))}
        </div>
      )}

      {tab === 'devices' && (
        <div className="space-y-3">
          {(data.sessions || []).length === 0 ? (
            <p className="rounded-2xl border border-zinc-800 p-8 text-center text-xs text-zinc-500">
              No session / device records.
            </p>
          ) : (
            data.sessions.map((s: any) => {
              const info = parseUa(s.userAgent);
              const Icon = info.device === 'Mobile' ? Smartphone : Monitor;
              return (
                <div
                  key={s.id}
                  className="flex flex-wrap items-start gap-3 rounded-2xl border border-zinc-800 bg-zinc-900/50 p-4"
                >
                  <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-zinc-800 text-zinc-300">
                    <Icon className="h-5 w-5" />
                  </span>
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="text-sm font-semibold text-white">
                        {info.browser} · {info.os}
                      </span>
                      <Badge variant={s.isActive ? 'emerald' : 'slate'}>
                        {s.isActive ? 'Active' : s.isRevoked ? 'Revoked' : 'Expired'}
                      </Badge>
                    </div>
                    <p className="mt-1 font-mono text-[11px] text-zinc-400">
                      IP {s.ipAddress || '—'} · {info.device}
                    </p>
                    <p className="mt-1 truncate text-[10px] text-zinc-600" title={s.userAgent}>
                      {s.userAgent || 'No user-agent'}
                    </p>
                    <p className="mt-1 text-[10px] text-zinc-500">
                      Started {new Date(s.createdAt).toLocaleString()} · Expires{' '}
                      {new Date(s.expiresAt).toLocaleString()}
                    </p>
                  </div>
                </div>
              );
            })
          )}
        </div>
      )}

      {tab === 'history' && (
        <div className="space-y-6">
          <HistoryBlock
            title="Contest entries"
            empty="No contest entries"
            rows={(data.gameHistory?.contests || []).map((e: any) => ({
              id: e._id,
              title: e.contestId?.title || 'Contest',
              meta: `Fee ${coins(e.contestId?.entryFee || 0)} · Pts ${e.totalPoints} · Rank ${
                e.rank ?? '—'
              } · Prize ${coins(e.prizeAmount)}`,
              when: e.createdAt,
            }))}
          />
          <HistoryBlock
            title="Fantasy teams"
            empty="No fantasy teams"
            rows={(data.gameHistory?.fantasyTeams || []).map((t: any) => ({
              id: t._id,
              title: t.name || 'Team',
              meta: `${t.matchId?.title || 'Match'} · Pts ${t.totalPoints} · Rank ${t.rank ?? '—'}`,
              when: t.createdAt,
            }))}
          />
          <HistoryBlock
            title="Pick Your Heroes"
            empty="No hero entries"
            rows={(data.gameHistory?.heroes || []).map((h: any) => ({
              id: h._id,
              title: h.contestId?.title || 'Heroes contest',
              meta: `Fee ${coins(h.contestId?.entryFee || 0)}`,
              when: h.createdAt,
            }))}
          />
        </div>
      )}

      {tab === 'pnl' && (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {[
            { label: 'Total deposited', value: pnl?.totalDeposited, tone: 'emerald' },
            { label: 'Total withdrawn', value: pnl?.totalWithdrawn, tone: 'rose' },
            { label: 'Contest fees paid', value: pnl?.contestFees, tone: 'rose' },
            { label: 'Contest winnings', value: pnl?.contestWinnings, tone: 'emerald' },
            { label: 'Admin credits', value: pnl?.adminCredits, tone: 'emerald' },
            { label: 'Admin debits', value: pnl?.adminDebits, tone: 'rose' },
            { label: 'Refunds', value: pnl?.refunds, tone: 'emerald' },
            { label: 'Net gaming', value: pnl?.netGaming, tone: 'neutral' },
            { label: 'Net cashflow', value: pnl?.netCashflow, tone: 'neutral' },
            { label: 'Estimated P&L', value: pnl?.estimatedPnL, tone: 'highlight' },
          ].map((c) => (
            <div
              key={c.label}
              className={`rounded-2xl border p-4 ${
                c.tone === 'highlight'
                  ? 'border-emerald-500/40 bg-emerald-500/10'
                  : 'border-zinc-800 bg-zinc-900/50'
              }`}
            >
              <div className="text-[10px] font-semibold uppercase text-zinc-500">{c.label}</div>
              <div
                className={`mt-2 font-mono text-xl font-bold ${
                  (c.value || 0) >= 0 ? 'text-emerald-400' : 'text-rose-400'
                }`}
              >
                {coins(c.value || 0)}
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal
        isOpen={coinOpen}
        onClose={() => setCoinOpen(false)}
        title={coinMode === 'deposit' ? 'Add Balance' : 'Deduct Balance'}
      >
        <form onSubmit={submitCoins} className="space-y-3 text-xs">
          <label className="block text-zinc-400">
            Amount (₹)
            <input
              type="number"
              min={1}
              required
              value={coinAmount}
              onChange={(e) => setCoinAmount(Number(e.target.value))}
              className="mt-1 w-full rounded-lg border border-zinc-800 bg-zinc-950 px-3 py-2 text-white"
            />
          </label>
          <label className="block text-zinc-400">
            Credit / Deduct From
            <select
              value={coinType}
              onChange={(e) => setCoinType(e.target.value as any)}
              className="mt-1 w-full rounded-lg border border-zinc-800 bg-zinc-950 px-3 py-2 text-white"
            >
              <option value="deposit">Deposit</option>
              <option value="winning">Winning</option>
              <option value="bonus">Bonus</option>
            </select>
          </label>
          <label className="block text-zinc-400">
            Reason (required)
            <textarea
              required
              minLength={5}
              rows={2}
              value={coinReason}
              onChange={(e) => setCoinReason(e.target.value)}
              className="mt-1 w-full rounded-lg border border-zinc-800 bg-zinc-950 px-3 py-2 text-white"
            />
          </label>
          <div className="flex justify-end gap-2 pt-2">
            <Button type="button" variant="secondary" onClick={() => setCoinOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" loading={busy} variant={coinMode === 'deduct' ? 'danger' : 'primary'}>
              Confirm
            </Button>
          </div>
        </form>
      </Modal>

      <Modal isOpen={pwOpen} onClose={() => setPwOpen(false)} title="Reset player password">
        <form onSubmit={submitPassword} className="space-y-3 text-xs">
          <label className="block text-zinc-400">
            New password (min 8)
            <input
              type="text"
              required
              minLength={8}
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="mt-1 w-full rounded-lg border border-zinc-800 bg-zinc-950 px-3 py-2 font-mono text-white"
            />
          </label>
          <p className="text-[10px] text-zinc-500">All active sessions will be revoked.</p>
          <div className="flex justify-end gap-2 pt-2">
            <Button type="button" variant="secondary" onClick={() => setPwOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" variant="amber" loading={busy}>
              Reset
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}

function HistoryBlock({
  title,
  empty,
  rows,
}: {
  title: string;
  empty: string;
  rows: { id: string; title: string; meta: string; when: string }[];
}) {
  return (
    <section className="overflow-hidden rounded-2xl border border-zinc-800 bg-zinc-900/50">
      <h2 className="border-b border-zinc-800 px-4 py-3 text-sm font-bold text-white">{title}</h2>
      {rows.length === 0 ? (
        <p className="p-6 text-center text-xs text-zinc-500">{empty}</p>
      ) : (
        <ul className="divide-y divide-zinc-800/60">
          {rows.map((r) => (
            <li key={r.id} className="px-4 py-3">
              <div className="text-sm font-medium text-white">{r.title}</div>
              <div className="mt-0.5 text-[11px] text-zinc-400">{r.meta}</div>
              <div className="mt-0.5 text-[10px] text-zinc-600">
                {new Date(r.when).toLocaleString()}
              </div>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}
