'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { Bell, CalendarDays, CheckCircle2, Copy, CreditCard, Edit3, Loader2, LockKeyhole, LogOut, Mail, MapPin, Package, Phone, ShieldCheck, ShoppingBag, Store, UserRound, WalletCards } from 'lucide-react';
import { Toaster, toast } from 'react-hot-toast';
import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';

const money = (value: unknown) => `${Number(value || 0).toLocaleString('vi-VN')}đ`;
const date = (value?: string) => value ? new Date(value).toLocaleString('vi-VN', { dateStyle: 'medium', timeStyle: 'short' }) : 'Chưa ghi nhận';

export default function UserProfilePage() {
  const user = useAuthStore((state) => state.user);
  const logout = useAuthStore((state) => state.logout);
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [telegramLinkLoading, setTelegramLinkLoading] = useState(false);

  useEffect(() => {
    let mounted = true;
    if (!user?.id) {
      setLoading(false);
      return () => { mounted = false; };
    }

    setLoading(true);
    // Không để một request bị treo khiến người dùng mắc kẹt ở màn hình loading.
    const timeout = window.setTimeout(() => {
      if (!mounted) return;
      setProfile((current: any) => current || user);
      setLoading(false);
      toast.error('Tải dữ liệu chi tiết quá lâu. Đang hiển thị thông tin tài khoản hiện có.');
    }, 10_000);

    api.get('/auth/profile')
      .then((response) => { if (mounted) setProfile(response.data); })
      .catch(() => {
        if (mounted) {
          setProfile(user);
          toast.error('Không thể tải dữ liệu chi tiết hồ sơ.');
        }
      })
      .finally(() => {
        window.clearTimeout(timeout);
        if (mounted) setLoading(false);
      });

    return () => {
      mounted = false;
      window.clearTimeout(timeout);
    };
  }, [user?.id]);

  const copyMemberCode = async () => {
    if (!profile?.memberCode) return;
    await navigator.clipboard.writeText(profile.memberCode);
    toast.success('Đã sao chép mã thành viên');
  };

  const requestTelegramLink = async () => {
    setTelegramLinkLoading(true);
    try {
      const response = await api.post('/telegram/link/request');
      const username = response.data.botUsername;
      const url = username ? `https://t.me/${username}?start=link_${response.data.token}` : null;
      if (url) window.open(url, '_blank', 'noopener,noreferrer');
      else toast.error('Telegram Bot chưa được cấu hình.');
    } catch {
      toast.error('Không thể tạo liên kết Telegram.');
    } finally {
      setTelegramLinkLoading(false);
    }
  };

  const unlinkTelegram = async () => {
    try {
      await api.post('/telegram/link/unlink');
      setProfile((current: any) => current ? { ...current, telegram: null } : current);
      toast.success('Đã hủy liên kết Telegram.');
    } catch {
      toast.error('Không thể hủy liên kết Telegram.');
    }
  };

  const toggleTelegramNotifications = async () => {
    const enabled = !profile?.telegram?.notificationEnabled;
    try {
      await api.post('/telegram/link/notifications', { enabled });
      setProfile((current: any) => current ? { ...current, telegram: { ...current.telegram, notificationEnabled: enabled } } : current);
    } catch {
      toast.error('Không thể cập nhật thông báo Telegram.');
    }
  };

  const role = profile?.role || user?.role || 'BUYER';
  const roleLabel = role === 'SELLER' ? 'Người bán uy tín' : role.includes('ADMIN') ? 'Quản trị viên' : 'Khách hàng';
  const socialLinks = [
    ['Facebook', profile?.facebookUrl], ['Discord', profile?.discordUrl], ['YouTube', profile?.youtubeUrl], ['Telegram', profile?.telegramUrl],
  ];

  if (loading) return <><Navbar /><div className="flex min-h-[calc(100vh-64px)] items-center justify-center bg-[#090a0d]"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div></>;

  return <>
    <Toaster />
    <Navbar />
    <main className="min-h-[calc(100vh-64px)] bg-[#090a0d] px-3 py-5 text-white sm:px-6 lg:px-8">
      <div className="mx-auto max-w-7xl">
        <section className="overflow-hidden rounded-2xl border border-white/10 bg-[#111214] shadow-2xl">
          <div className="h-28 bg-[radial-gradient(circle_at_20%_0%,rgba(0,191,255,.42),transparent_38%),radial-gradient(circle_at_75%_10%,rgba(239,68,68,.35),transparent_35%),linear-gradient(110deg,#101c42,#101114_50%,#27120f)] sm:h-40" />
          <div className="relative flex flex-col gap-4 px-5 pb-5 sm:flex-row sm:items-end sm:justify-between sm:px-7">
            <div className="-mt-11 flex min-w-0 items-end gap-4 sm:-mt-14">
              <div className="flex h-24 w-24 shrink-0 items-center justify-center rounded-2xl border-4 border-[#111214] bg-gradient-to-br from-cyan-500 to-violet-600 text-4xl font-black shadow-lg">{(profile?.name || user?.name || 'U').charAt(0).toUpperCase()}</div>
              <div className="pb-1"><div className="flex flex-wrap items-center gap-2"><h1 className="text-2xl font-black">{profile?.name || user?.name || 'Chưa cập nhật'}</h1><span className="rounded-full bg-violet-500/15 px-2.5 py-1 text-xs font-bold text-violet-300">{roleLabel}</span><span className="rounded-full bg-emerald-500/15 px-2.5 py-1 text-xs font-bold text-emerald-300">Đang hoạt động</span></div><p className="mt-1 text-sm text-gray-400">{profile?.email || user?.email}</p><button onClick={copyMemberCode} className="mt-1 inline-flex items-center gap-1 font-mono text-xs text-cyan-300 hover:text-cyan-200">Mã thành viên: {profile?.memberCode || '—'} <Copy className="h-3 w-3" /></button></div>
            </div>
            <Link href="/vi/profile/edit" className="inline-flex shrink-0 items-center justify-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-black text-white hover:bg-primary/90"><Edit3 className="h-4 w-4" /> Chỉnh sửa hồ sơ</Link>
          </div>
        </section>

        <section className="mt-3 grid grid-cols-2 overflow-hidden rounded-xl border border-white/10 bg-[#111214] sm:grid-cols-3 lg:grid-cols-6">
          {[
            [ShoppingBag, profile?.stats?.buyerOrders ?? 0, 'Đơn đã mua'], [Store, profile?.stats?.sellerOrders ?? 0, 'Đơn đã bán'], [WalletCards, money(profile?.balance), 'Số dư ví'], [CreditCard, money(profile?.pendingBalance), 'Số dư chờ'], [CalendarDays, profile?.createdAt ? new Date(profile.createdAt).toLocaleDateString('vi-VN') : '—', 'Ngày tham gia'], [ShieldCheck, profile?.emailVerified ? 'Đã xác minh' : 'Chưa xác minh', 'Email'],
          ].map(([Icon, value, label]: any) => <div key={label} className="flex items-center gap-3 border-b border-r border-white/10 p-3 last:border-r-0 sm:p-4"><div className="rounded-lg bg-primary/10 p-2 text-primary"><Icon className="h-4 w-4" /></div><div><p className="text-base font-black leading-tight">{value}</p><p className="mt-1 text-[10px] font-bold uppercase tracking-wide text-gray-500">{label}</p></div></div>)}
        </section>

        <section className="mt-3 grid gap-3 lg:grid-cols-3">
          <article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="flex items-center gap-2 font-black"><UserRound className="h-5 w-5 text-primary" /> Thông tin cá nhân</h2><div className="mt-5 space-y-3 text-sm">{[['Email', profile?.email || '—', Mail], ['Số điện thoại', profile?.phone || 'Chưa cung cấp', Phone], ['Khu vực', profile?.city || 'Chưa cung cấp', MapPin], ['Vai trò', roleLabel, ShieldCheck], ['Truy cập gần nhất', date(profile?.lastActiveAt), CalendarDays]].map(([label, value, Icon]: any) => <div key={label} className="flex items-start gap-3"><Icon className="mt-0.5 h-4 w-4 shrink-0 text-gray-500" /><div><p className="text-xs text-gray-500">{label}</p><p className="mt-0.5 font-semibold text-gray-200">{value}</p></div></div>)}</div><Link href="/vi/profile/edit" className="mt-5 flex items-center justify-center rounded-lg bg-primary/10 px-3 py-2.5 text-sm font-bold text-primary hover:bg-primary/20">Xem và chỉnh sửa thông tin</Link></article>

          <article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="flex items-center gap-2 font-black"><Store className="h-5 w-5 text-amber-300" /> Thống kê giao dịch</h2><div className="mt-5 grid grid-cols-2 gap-3">{[['Đơn đã mua', profile?.stats?.buyerOrders ?? 0], ['Hoàn thành', profile?.stats?.completedBuyerOrders ?? 0], ['Đơn đã bán', profile?.stats?.sellerOrders ?? 0], ['Số dư khả dụng', money(profile?.balance)]].map(([label, value]) => <div key={label} className="rounded-lg border border-white/10 bg-black/20 p-3"><p className="text-xs text-gray-500">{label}</p><p className="mt-1 text-lg font-black text-gray-100">{value}</p></div>)}</div><Link href="/vi/orders" className="mt-5 flex items-center justify-center rounded-lg bg-primary/10 px-3 py-2.5 text-sm font-bold text-primary hover:bg-primary/20">Xem đơn hàng</Link></article>

          <article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="flex items-center gap-2 font-black"><LockKeyhole className="h-5 w-5 text-rose-300" /> Bảo mật tài khoản</h2><div className="mt-4 space-y-2">{[['Đăng nhập hai lớp (2FA)', profile?.twoFactorEnabled ? 'Đã bật' : 'Chưa bật', profile?.twoFactorEnabled], ['Email xác minh', profile?.emailVerified ? 'Đã xác minh' : 'Chưa xác minh', profile?.emailVerified], ['Số điện thoại', profile?.phone ? 'Đã cung cấp' : 'Chưa cung cấp', Boolean(profile?.phone)]].map(([label, value, good]: any) => <div key={label} className="flex items-center justify-between rounded-lg bg-black/20 px-3 py-3"><span className="text-sm text-gray-300">{label}</span><span className={`text-xs font-bold ${good ? 'text-emerald-400' : 'text-amber-300'}`}>{value}</span></div>)}</div><Link href="/vi/profile/edit" className="mt-5 flex items-center justify-center rounded-lg bg-primary/10 px-3 py-2.5 text-sm font-bold text-primary hover:bg-primary/20">Quản lý bảo mật</Link></article>
        </section>

        <section className="mt-3 grid gap-3 lg:grid-cols-3"><article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="font-black">Liên kết mạng xã hội</h2><div className="mt-4 space-y-2">{socialLinks.map(([name, url]) => <button key={name} onClick={() => url ? window.open(url, '_blank', 'noreferrer') : toast('Chưa liên kết, hãy cập nhật trong chỉnh sửa hồ sơ.')} className="flex w-full items-center justify-between rounded-lg bg-black/20 px-3 py-3 text-left hover:bg-white/5"><span className="text-sm font-semibold text-gray-300">{name}</span><span className={url ? 'text-xs font-bold text-emerald-400' : 'text-xs font-bold text-gray-500'}>{url ? 'Đã kết nối' : 'Kết nối'}</span></button>)}</div></article><article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="flex items-center justify-between font-black">Đơn hàng gần đây <Link href="/vi/orders" className="text-xs text-primary">Xem tất cả</Link></h2><div className="mt-4 space-y-2">{profile?.recentOrders?.length ? profile.recentOrders.map((order: any) => <div key={order.id} className="rounded-lg border border-white/5 bg-black/20 p-3"><p className="truncate text-sm font-bold">{order.productName}</p><div className="mt-1 flex justify-between text-xs text-gray-500"><span>#{order.id.slice(0, 8)} · {order.status}</span><span>{money(order.totalAmount)}</span></div></div>) : <p className="rounded-lg border border-dashed border-white/10 p-5 text-center text-sm text-gray-500">Chưa có đơn hàng gần đây.</p>}</div></article><article className="rounded-xl border border-white/10 bg-[#111214] p-5"><h2 className="flex items-center gap-2 font-black"><Bell className="h-5 w-5 text-amber-300" /> Hoạt động gần đây</h2><div className="mt-4 space-y-2">{profile?.recentNotifications?.length ? profile.recentNotifications.map((note: any) => <div key={note.id} className="flex gap-3 rounded-lg bg-black/20 p-3"><CheckCircle2 className={`mt-0.5 h-3.5 w-3.5 ${note.isRead ? 'text-gray-600' : 'text-emerald-400'}`} /><div className="min-w-0"><p className="truncate text-sm font-semibold">{note.title}</p><p className="mt-1 text-xs text-gray-500">{date(note.createdAt)}</p></div></div>) : <p className="rounded-lg border border-dashed border-white/10 p-5 text-center text-sm text-gray-500">Chưa có hoạt động gần đây.</p>}</div></article></section>

        <section className="mt-3 flex flex-col gap-3 rounded-xl border border-primary/20 bg-primary/5 p-4 text-sm sm:flex-row sm:items-center sm:justify-between"><div><p className="font-bold text-gray-100">Giao dịch an toàn trên SHOPMMO</p><p className="mt-1 text-xs text-gray-500">Bảo vệ người mua, quy trình rõ ràng và hỗ trợ khi cần.</p></div><button onClick={() => { logout(); window.location.href = '/vi/auth/login'; }} className="inline-flex items-center justify-center gap-2 rounded-lg border border-red-500/30 px-3 py-2 text-xs font-bold text-red-300 hover:bg-red-500/10"><LogOut className="h-4 w-4" /> Đăng xuất</button></section>
        <section className="mt-3 rounded-xl border border-cyan-400/20 bg-cyan-400/5 p-5"><div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"><div><h2 className="font-black text-cyan-100">Liên kết Telegram</h2><p className="mt-1 text-sm text-gray-400">Dùng Telegram để đăng nhập nhanh và nhận thông báo an toàn.</p>{profile?.telegram?.telegramUserId && <p className="mt-2 text-xs text-emerald-300">Đã liên kết{profile.telegram.username ? `: @${profile.telegram.username}` : ''}</p>}</div><button type="button" onClick={requestTelegramLink} disabled={telegramLinkLoading} className="rounded-lg bg-cyan-500 px-4 py-2.5 text-sm font-bold text-slate-950 hover:bg-cyan-400 disabled:opacity-60">{telegramLinkLoading ? 'Đang tạo liên kết...' : profile?.telegram?.telegramUserId ? 'Liên kết lại' : 'Liên kết Telegram'}</button></div></section>
        {profile?.telegram?.telegramUserId && <section className="mt-3 flex flex-wrap gap-3 rounded-xl border border-white/10 bg-[#111214] p-5"><button type="button" onClick={toggleTelegramNotifications} className="rounded-lg bg-white/10 px-4 py-2 text-sm font-bold text-gray-200">{profile.telegram.notificationEnabled ? 'Tắt thông báo Telegram' : 'Bật thông báo Telegram'}</button><button type="button" onClick={unlinkTelegram} className="rounded-lg bg-red-500/10 px-4 py-2 text-sm font-bold text-red-300">Hủy liên kết Telegram</button></section>}
      </div>
    </main>
  </>;
}
