'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  User, Mail, Lock, Coins, History, Receipt, RefreshCw, Check, X,
  Loader2, QrCode, BarChart2, Eye, EyeOff, ChevronRight, Zap, AlertCircle,
} from 'lucide-react';
import type { QRUser } from './AuthModal';

interface AccountPanelProps {
  user: QRUser;
  token: string;
  onUserUpdate: (u: QRUser) => void;
  onTopupRequired: () => void;
}

interface HistoryItem {
  id: string;
  type: string;
  content: string;
  credits_used: number;
  created_at: string;
}

interface TopupItem {
  id: string;
  credits: number;
  amount_usd: string;
  payment_ref: string;
  status: string;
  created_at: string;
}

const FREE_LIMIT = 10;

type Section = 'overview' | 'history' | 'spending' | 'profile';

export default function AccountPanel({ user, token, onUserUpdate, onTopupRequired }: AccountPanelProps) {
  const [section, setSection] = useState<Section>('overview');

  // Profile edit state
  const [name, setName] = useState(user.name);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [profileLoading, setProfileLoading] = useState(false);
  const [profileMsg, setProfileMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);

  // History state
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [historyLoaded, setHistoryLoaded] = useState(false);

  // Spending state
  const [topups, setTopups] = useState<TopupItem[]>([]);
  const [topupsLoading, setTopupsLoading] = useState(false);
  const [topupsLoaded, setTopupsLoaded] = useState(false);

  const loadHistory = useCallback(async () => {
    setHistoryLoading(true);
    try {
      const r = await fetch('/api/qr/history', { headers: { Authorization: `Bearer ${token}` } });
      if (r.ok) { const d = await r.json(); setHistory(d.history); setHistoryLoaded(true); }
    } finally { setHistoryLoading(false); }
  }, [token]);

  const loadTopups = useCallback(async () => {
    setTopupsLoading(true);
    try {
      const r = await fetch('/api/qr/topups', { headers: { Authorization: `Bearer ${token}` } });
      if (r.ok) { const d = await r.json(); setTopups(d.topups); setTopupsLoaded(true); }
    } finally { setTopupsLoading(false); }
  }, [token]);

  useEffect(() => {
    if (section === 'history' && !historyLoaded) loadHistory();
    if (section === 'spending' && !topupsLoaded) loadTopups();
  }, [section, historyLoaded, topupsLoaded, loadHistory, loadTopups]);

  async function saveProfile() {
    setProfileMsg(null);
    setProfileLoading(true);
    try {
      const body: Record<string, string> = {};
      if (name !== user.name) body.name = name;
      if (newPassword) { body.currentPassword = currentPassword; body.newPassword = newPassword; }
      const r = await fetch('/api/qr/auth/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify(body),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error);
      onUserUpdate({ ...user, name: data.name });
      setCurrentPassword(''); setNewPassword('');
      setProfileMsg({ type: 'ok', text: 'Profile updated successfully' });
    } catch (err: unknown) {
      setProfileMsg({ type: 'err', text: err instanceof Error ? err.message : 'Update failed' });
    } finally { setProfileLoading(false); }
  }

  const freeLeft = Math.max(0, FREE_LIMIT - (user.freeGensToday ?? 0));
  const freePercent = Math.round((freeLeft / FREE_LIMIT) * 100);
  const hasChanges = name !== user.name || newPassword.length > 0;

  const NAV: { id: Section; label: string; icon: typeof User }[] = [
    { id: 'overview', label: 'Overview', icon: User },
    { id: 'history', label: 'Generation History', icon: History },
    { id: 'spending', label: 'Spending', icon: Receipt },
    { id: 'profile', label: 'Profile & Password', icon: Lock },
  ];

  return (
    <div className="flex flex-col sm:flex-row gap-4 min-h-[480px]">
      {/* ── Sidebar nav ──────────────────────────────────────────────────── */}
      <nav className="sm:w-44 shrink-0 flex sm:flex-col gap-1">
        {NAV.map(n => (
          <button
            key={n.id}
            onClick={() => setSection(n.id)}
            className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-medium transition-all text-left w-full ${
              section === n.id
                ? 'bg-indigo-600/20 border border-indigo-500/40 text-indigo-200'
                : 'text-slate-400 hover:text-slate-200 hover:bg-white/[0.04]'
            }`}
          >
            <n.icon size={14} className="shrink-0" />
            <span className="hidden sm:inline">{n.label}</span>
          </button>
        ))}
      </nav>

      {/* ── Content ──────────────────────────────────────────────────────── */}
      <div className="flex-1 min-w-0">

        {/* Overview */}
        {section === 'overview' && (
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white">Account Overview</h3>

            {/* Identity */}
            <div className="flex items-center gap-4 p-4 bg-white/[0.03] border border-slate-700/50 rounded-2xl">
              <div className="w-12 h-12 rounded-full bg-indigo-600/20 border border-indigo-500/30 flex items-center justify-center shrink-0">
                <span className="text-lg font-bold text-indigo-300">{(user.name || user.email)[0].toUpperCase()}</span>
              </div>
              <div>
                <p className="font-semibold text-white">{user.name || '(no name)'}</p>
                <p className="text-sm text-slate-500">{user.email}</p>
                <span className="text-xs px-2 py-0.5 rounded-full bg-slate-700/60 text-slate-400 capitalize mt-1 inline-block">{user.plan} plan</span>
              </div>
            </div>

            {/* Credits */}
            <div className="grid grid-cols-2 gap-3">
              <div className="p-4 bg-amber-500/8 border border-amber-500/20 rounded-2xl">
                <div className="flex items-center gap-2 mb-1">
                  <Coins size={14} className="text-amber-400" />
                  <span className="text-xs text-amber-400 font-medium">Credits</span>
                </div>
                <p className="text-2xl font-bold text-amber-300">{user.credits}</p>
                <button onClick={onTopupRequired} className="mt-2 flex items-center gap-1 text-xs text-amber-500 hover:text-amber-300 transition-colors">
                  <Zap size={11} /> Top up <ChevronRight size={11} />
                </button>
              </div>
              <div className={`p-4 border rounded-2xl ${freeLeft > 0 ? 'bg-emerald-500/8 border-emerald-500/20' : 'bg-slate-800/40 border-slate-700/50'}`}>
                <div className="flex items-center gap-2 mb-1">
                  <QrCode size={14} className={freeLeft > 0 ? 'text-emerald-400' : 'text-slate-500'} />
                  <span className={`text-xs font-medium ${freeLeft > 0 ? 'text-emerald-400' : 'text-slate-500'}`}>Free today</span>
                </div>
                <p className={`text-2xl font-bold ${freeLeft > 0 ? 'text-emerald-300' : 'text-slate-500'}`}>{freeLeft}<span className="text-base font-normal text-slate-600">/{FREE_LIMIT}</span></p>
                <div className="mt-2 h-1.5 bg-slate-700/60 rounded-full overflow-hidden">
                  <div className="h-full bg-emerald-500 rounded-full transition-all" style={{ width: `${freePercent}%` }} />
                </div>
              </div>
            </div>

            {/* Quick actions */}
            <div className="grid grid-cols-3 gap-2">
              {[
                { label: 'View History', icon: History, action: () => setSection('history') },
                { label: 'Spending', icon: Receipt, action: () => setSection('spending') },
                { label: 'Edit Profile', icon: User, action: () => setSection('profile') },
              ].map(a => (
                <button key={a.label} onClick={a.action} className="flex flex-col items-center gap-2 p-3 bg-white/[0.03] hover:bg-white/[0.05] border border-slate-700/40 hover:border-slate-600/60 rounded-xl transition-all group">
                  <a.icon size={16} className="text-slate-400 group-hover:text-slate-200 transition-colors" />
                  <span className="text-xs text-slate-500 group-hover:text-slate-300 transition-colors">{a.label}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* History */}
        {section === 'history' && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold text-white">Generation History</h3>
              <button onClick={loadHistory} disabled={historyLoading} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-300 transition-colors disabled:opacity-50">
                <RefreshCw size={12} className={historyLoading ? 'animate-spin' : ''} /> Refresh
              </button>
            </div>
            {historyLoading ? (
              <div className="text-center py-10 text-slate-500 text-sm flex items-center justify-center gap-2">
                <Loader2 size={15} className="animate-spin" /> Loading…
              </div>
            ) : history.length === 0 ? (
              <div className="text-center py-10 text-slate-600 text-sm">No generations yet</div>
            ) : (
              <div className="space-y-1.5">
                {history.map(h => (
                  <div key={h.id} className="flex items-center gap-3 px-4 py-3 bg-white/[0.02] border border-slate-700/30 rounded-xl hover:border-slate-600/40 transition-colors">
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${h.type === 'qr' ? 'bg-indigo-600/20' : 'bg-purple-600/20'}`}>
                      {h.type === 'qr' ? <QrCode size={14} className="text-indigo-400" /> : <BarChart2 size={14} className="text-purple-400" />}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-mono text-slate-300 truncate">{h.content}</p>
                      <p className="text-xs text-slate-600 mt-0.5">
                        {h.type.toUpperCase()} · {new Date(h.created_at).toLocaleDateString('en-HK', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                      </p>
                    </div>
                    <div className={`text-xs px-2 py-0.5 rounded-md shrink-0 ${h.credits_used === 0 ? 'bg-emerald-500/10 text-emerald-400' : 'bg-amber-500/10 text-amber-400'}`}>
                      {h.credits_used === 0 ? 'Free' : `${h.credits_used}cr`}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Spending */}
        {section === 'spending' && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold text-white">Spending History</h3>
              <button onClick={loadTopups} disabled={topupsLoading} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-300 transition-colors disabled:opacity-50">
                <RefreshCw size={12} className={topupsLoading ? 'animate-spin' : ''} /> Refresh
              </button>
            </div>

            {/* Balance summary */}
            <div className="flex items-center gap-3 p-4 bg-amber-500/8 border border-amber-500/20 rounded-2xl">
              <Coins size={20} className="text-amber-400 shrink-0" />
              <div>
                <p className="text-xs text-amber-500 font-medium">Current balance</p>
                <p className="text-xl font-bold text-amber-300">{user.credits} credits</p>
              </div>
              <button onClick={onTopupRequired} className="ml-auto flex items-center gap-1.5 px-3 py-1.5 bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/30 text-amber-300 text-xs font-medium rounded-xl transition-colors">
                <Zap size={12} /> Top up
              </button>
            </div>

            {topupsLoading ? (
              <div className="text-center py-10 text-slate-500 text-sm flex items-center justify-center gap-2">
                <Loader2 size={15} className="animate-spin" /> Loading…
              </div>
            ) : topups.length === 0 ? (
              <div className="text-center py-10 text-slate-600 text-sm">No purchases yet</div>
            ) : (
              <div className="space-y-1.5">
                {topups.map(t => (
                  <div key={t.id} className="flex items-center gap-3 px-4 py-3 bg-white/[0.02] border border-slate-700/30 rounded-xl">
                    <div className="w-8 h-8 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0">
                      <Receipt size={14} className="text-amber-400" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-white">+{t.credits} credits</p>
                      <p className="text-xs text-slate-600 mt-0.5">
                        {new Date(t.created_at).toLocaleDateString('en-HK', { year: 'numeric', month: 'short', day: 'numeric' })}
                        {' · '}<span className="font-mono text-slate-700">{t.payment_ref}</span>
                      </p>
                    </div>
                    <div className="text-right shrink-0">
                      <p className="text-sm font-semibold text-white">${parseFloat(t.amount_usd).toFixed(2)}</p>
                      <span className={`text-xs px-2 py-0.5 rounded-md ${t.status === 'completed' ? 'bg-emerald-500/10 text-emerald-400' : 'bg-slate-700/60 text-slate-400'}`}>
                        {t.status}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Profile */}
        {section === 'profile' && (
          <div className="space-y-5 max-w-md">
            <h3 className="text-sm font-semibold text-white">Profile & Password</h3>

            {/* Email (read-only) */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">Email</label>
              <div className="relative">
                <Mail size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-600" />
                <input disabled value={user.email} className="w-full bg-slate-800/30 border border-slate-700/40 rounded-xl pl-9 pr-4 py-2.5 text-sm text-slate-500 cursor-not-allowed" />
              </div>
              <p className="text-xs text-slate-600 mt-1">Email address cannot be changed</p>
            </div>

            {/* Name */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">Display Name</label>
              <div className="relative">
                <User size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
                <input
                  type="text" value={name} onChange={e => setName(e.target.value)}
                  placeholder="Your name"
                  className="w-full bg-slate-800/60 border border-slate-700/60 rounded-xl pl-9 pr-4 py-2.5 text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40 transition-colors"
                />
              </div>
            </div>

            {/* Password change */}
            <div className="pt-3 border-t border-slate-700/40">
              <p className="text-xs font-semibold text-slate-300 mb-3">Change Password</p>
              <div className="space-y-3">
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1.5">Current Password</label>
                  <div className="relative">
                    <Lock size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
                    <input
                      type={showCurrent ? 'text' : 'password'} value={currentPassword} onChange={e => setCurrentPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full bg-slate-800/60 border border-slate-700/60 rounded-xl pl-9 pr-10 py-2.5 text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40 transition-colors"
                    />
                    <button type="button" onClick={() => setShowCurrent(v => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300">
                      {showCurrent ? <EyeOff size={14} /> : <Eye size={14} />}
                    </button>
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-400 mb-1.5">New Password</label>
                  <div className="relative">
                    <Lock size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
                    <input
                      type={showNew ? 'text' : 'password'} value={newPassword} onChange={e => setNewPassword(e.target.value)}
                      placeholder="Minimum 8 characters"
                      className="w-full bg-slate-800/60 border border-slate-700/60 rounded-xl pl-9 pr-10 py-2.5 text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40 transition-colors"
                    />
                    <button type="button" onClick={() => setShowNew(v => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300">
                      {showNew ? <EyeOff size={14} /> : <Eye size={14} />}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {profileMsg && (
              <div className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm border ${profileMsg.type === 'ok' ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400' : 'bg-red-500/10 border-red-500/30 text-red-400'}`}>
                {profileMsg.type === 'ok' ? <Check size={14} /> : <AlertCircle size={14} />}
                {profileMsg.text}
              </div>
            )}

            <button
              onClick={saveProfile} disabled={profileLoading || !hasChanges}
              className="flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white font-medium text-sm rounded-xl transition-colors"
            >
              {profileLoading ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}
              {profileLoading ? 'Saving…' : 'Save Changes'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
