'use client';

import Link from 'next/link';
import {
  Wallet as WalletIcon,
  Activity,
  ArrowDownLeft,
  ArrowUpRight,
  ArrowUpRight as ExternalArrow,
  Users,
  User,
  Shield,
  Menu,
  X,
  CreditCard,
  LockKeyhole,
  TrendingUp,
  ArrowRight,
  Star,
  Zap,
  BarChart3,
  History,
  Headphones,
  Gift,
  RefreshCw,
  ShoppingCart,
} from 'lucide-react';
import { StatCard } from '@/components/ui/stat-card';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/empty-state';
import { Button } from '@/components/ui/button';
import { useEffect, useState } from 'react';
import { formatCurrency, formatDateTime, formatDate, getDisplayName } from '@/lib/utils';
import { useAuth } from '@/hooks/useAuth';
import { walletService, type Wallet, type WalletHistoryItem } from '@/services/wallet.service';
import { useSocket } from '@/context/SocketContext';
import { SOCKET_EVENTS } from '@/config/socket.config';
import type { WalletBalanceChangedPayload } from '@/types/socket.types';
import { userService, type UserBusinessRules } from '@/services/user.service';
import { finesService } from '@/services/fines.service';
import { obligationsService } from '@/services/obligations.service';
import { businessRulesService } from '@/services/business-rules.service';
import { getReferralDashboard } from '@/services/referral/referral.service';
import { DashboardPopups } from '@/components/dashboard-popups';

const statusVariant: Record<string, 'success' | 'warning' | 'danger'> = {
  COMPLETED: 'success',
  PENDING: 'warning',
  FAILED: 'danger',
  CANCELLED: 'danger',
  REVERSED: 'danger',
};

export default function UserDashboardOverviewPage() {
  const { user } = useAuth();
  const { socket } = useSocket();
  const [loading, setLoading] = useState(true);
  const [wallet, setWallet] = useState<Wallet | null>(null);
  const [recent, setRecent] = useState<WalletHistoryItem[]>([]);
  const [businessRules, setBusinessRules] = useState<UserBusinessRules | null>(null);
  const [orderLimits, setOrderLimits] = useState<{ minAmount: number; maxAmount?: number; dailyLimit: number; dailyUsed: number; dailyRemaining: number } | null>(null);
  const [finesStats, setFinesStats] = useState<{ totalPending: string; totalActive: string } | null>(null);
  const [obligationStats, setObligationStats] = useState<{ totalPending: string; totalOverdue: string; countPending: number; countOverdue: number } | null>(null);
  const [referralIncome, setReferralIncome] = useState<number | null>(null);
  const [dashboardError, setDashboardError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const [walletRes, historyRes, rulesRes, limitsRes, finesRes, oblRes, refRes] = await Promise.allSettled([
          walletService.getWallet(),
          walletService.getHistory({ limit: 6 }),
          userService.getBusinessRules(),
          businessRulesService.getOrderLimits(user?.id ?? ''),
          finesService.getFinesStats(),
          obligationsService.getObligationStats(),
          getReferralDashboard().catch(() => null),
        ]);
        if (!active) return;

        if (walletRes.status === 'fulfilled') setWallet(walletRes.value);
        if (historyRes.status === 'fulfilled') setRecent(historyRes.value?.data ?? []);
        if (rulesRes.status === 'fulfilled') setBusinessRules(rulesRes.value);
        if (limitsRes.status === 'fulfilled') setOrderLimits(limitsRes.value);
        if (finesRes.status === 'fulfilled') setFinesStats(finesRes.value);
        if (oblRes.status === 'fulfilled') setObligationStats(oblRes.value);
        if (refRes.status === 'fulfilled' && refRes.value) {
          setReferralIncome(Number((refRes.value as any).referralIncome) || 0);
        }
      } catch {
        if (active) setDashboardError('Failed to load dashboard data.');
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user?.id]);

  useEffect(() => {
    if (!socket) return;

    const handleBalanceChange = (payload: WalletBalanceChangedPayload) => {
      setWallet((prev) => {
        if (!prev || prev.userId !== payload.userId) return prev;
        return {
          ...prev,
          balance: payload.newBalance,
          locked: payload.locked,
          available: payload.available,
        };
      });
    };

    socket.on(SOCKET_EVENTS.WALLET_BALANCE_CHANGED, handleBalanceChange);

    return () => {
      socket.off(SOCKET_EVENTS.WALLET_BALANCE_CHANGED, handleBalanceChange);
    };
  }, [socket]);

  const displayName = getDisplayName(user);

  return (
    <div className="space-y-6">
      <DashboardPopups />
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-ink">
            Welcome back, {displayName}
          </h1>
          <p className="mt-1 text-sm text-ink-muted">
            Here&apos;s a summary of your wallet today.
          </p>
        </div>
          <div className="flex items-center gap-2">
            <Link
              href="/dashboard/referral"
              className="inline-flex items-center gap-1.5 rounded-xl border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink transition-colors hover:bg-surface-raised"
            >
              <Users className="h-4 w-4" />
              Refer Friends
            </Link>
            <Link
              href="/dashboard/buy"
              className="inline-flex items-center gap-1.5 rounded-xl bg-primary-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-700"
            >
              <ShoppingCart className="h-4 w-4" />
              Buy
            </Link>
            <Link
              href="/dashboard/sell"
              className="inline-flex items-center gap-1.5 rounded-xl border border-primary-600 bg-primary-50 px-3 py-1.5 text-sm font-medium text-primary-700 transition-colors hover:bg-primary-100 dark:bg-primary-950/30 dark:text-primary-300 dark:hover:bg-primary-950/50"
            >
              <TrendingUp className="h-4 w-4" />
              Sell
            </Link>
          </div>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {loading ? (
          Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="card p-5">
              <Skeleton className="h-4 w-24" />
              <Skeleton className="mt-3 h-8 w-32" />
            </div>
          ))
        ) : (
          <>
            <StatCard
              label="Total Balance"
              value={formatCurrency(wallet?.balance ?? 0)}
              icon={WalletIcon}
              iconClass="bg-primary-100 text-primary-600 dark:bg-primary-500/15 dark:text-primary-300"
            />
            <StatCard
              label="Available"
              value={formatCurrency(wallet?.available ?? 0)}
              icon={Activity}
              iconClass="bg-emerald-100 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-300"
            />
            <StatCard
              label="Locked"
              value={formatCurrency(wallet?.locked ?? 0)}
              icon={LockKeyhole}
              iconClass="bg-amber-100 text-amber-600 dark:bg-amber-500/15 dark:text-amber-300"
            />
            <StatCard
              label="Referral Rewards"
              value={referralIncome === null ? '—' : formatCurrency(referralIncome)}
              icon={Users}
              iconClass="bg-violet-100 text-violet-600 dark:bg-violet-500/15 dark:text-violet-300"
            />
          </>
        )}
      </div>

      {/* Main grid */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Recent transactions */}
        <Card className="lg:col-span-2">
          <CardHeader className="flex-row items-center justify-between space-y-0">
            <div>
              <CardTitle>Recent Transactions</CardTitle>
              <CardDescription className="mt-1">Latest activity across your wallet</CardDescription>
            </div>
            <Link href="/dashboard/transactions" className="text-sm font-medium text-primary-600 hover:underline">
              View all
            </Link>
          </CardHeader>
          <CardContent>
            <div className="divide-y divide-line">
              {loading
                ? Array.from({ length: 5 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-4 py-4">
                      <Skeleton className="h-10 w-10 rounded-xl" />
                      <div className="flex-1 space-y-2">
                        <Skeleton className="h-3 w-40" />
                        <Skeleton className="h-3 w-24" />
                      </div>
                      <Skeleton className="h-4 w-20" />
                    </div>
                  ))
                : recent.length === 0 && (
                    <div className="py-10">
                      <EmptyState
                        icon={History}
                        title="No transactions yet"
                        description="Your completed activity will appear here."
                        action={
                          <Link href="/dashboard/referral">
                            <Button size="sm">Invite Friends</Button>
                          </Link>
                        }
                      />
                    </div>
                  )}
              {recent.map((tx) => {
                const isCredit = tx.amount >= 0;
                return (
                  <div key={tx.id} className="flex items-center gap-4 py-4 first:pt-0 last:pb-0">
                    <div
                      className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${
                        isCredit ? 'bg-emerald-500/10 text-emerald-500' : 'bg-surface-raised text-ink-muted'
                      }`}
                    >
                      {isCredit ? <ArrowDownLeft className="h-4 w-4" /> : <ArrowUpRight className="h-4 w-4" />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium text-ink">
                        {tx.description || tx.type.replace('_', ' ')}
                      </p>
                      <p className="text-xs text-ink-faint">{formatDateTime(tx.createdAt)}</p>
                    </div>
                    <div className="text-right">
                      <p className={`text-sm font-semibold ${isCredit ? 'text-emerald-500' : 'text-ink'}`}>
                        {isCredit ? '+' : ''}
                        {formatCurrency(tx.amount)}
                      </p>
                      {tx.status && (
                        <Badge variant={statusVariant[tx.status] ?? 'success'} className="mt-0.5">
                          {tx.status.toLowerCase()}
                        </Badge>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>

        {/* Quick actions */}
        <Card>
          <CardHeader>
            <CardTitle>Quick Actions</CardTitle>
            <CardDescription className="mt-1">Manage your account</CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            <QuickActionItem href="/dashboard/transactions" icon={History} label="Transactions" desc="View your full history" />
            <QuickActionItem href="/dashboard/referral" icon={Users} label="Refer Friends" desc="Earn referral rewards" />
            <QuickActionItem href="/dashboard/profile" icon={User} label="My Profile" desc="Manage your account" />
            <QuickActionItem href="/dashboard/appeals" icon={Shield} label="Appeals" desc="View or create appeals" />
          </CardContent>
        </Card>
      </div>

      {/* Status strip */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Account Status */}
        <Card>
          <CardHeader>
            <CardTitle>Account Status</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <StatusRow label="Email verified" ok={Boolean(user?.isEmailVerified)} />
            <StatusRow label="Two-factor auth" ok={Boolean(user?.isTwoFactorEnabled)} />
            <StatusRow label="Wallet active" ok={wallet ? !wallet.isFrozen : true} />
          </CardContent>
        </Card>

        {/* Tier & Limits */}
        <Card>
          <CardHeader>
            <CardTitle>Tier & Limits</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {loading ? (
              Array.from({ length: 4 }).map((_, i) => (
                <Skeleton key={i} className="h-5 w-full" />
              ))
            ) : businessRules ? (
              <>
                <InfoRow label="Tier" value={businessRules.tierName || businessRules.tier} />
                <InfoRow label="Min Purchase" value={formatCurrency(businessRules.minPurchaseAmount, businessRules.currency)} />
                {businessRules.maxPurchaseAmount && (
                  <InfoRow label="Max Purchase" value={formatCurrency(businessRules.maxPurchaseAmount, businessRules.currency)} />
                )}
                {orderLimits && (
                  <>
                    <InfoRow label="Daily Order Limit" value={`${orderLimits.dailyUsed} / ${orderLimits.dailyLimit}`} />
                    <InfoRow label="Daily Remaining" value={String(orderLimits.dailyRemaining)} />
                  </>
                )}
              </>
            ) : (
              <p className="text-sm text-ink-muted">No tier info available</p>
            )}
          </CardContent>
        </Card>

        {/* Subscription & Obligations - only show when wallet is frozen, has pending/active fines, or has pending/overdue obligations. The subscription plan itself is backend-only and does not need to be surfaced to the user. */}
        {(() => {
          const isWalletFrozen = wallet?.isFrozen === true;
          const hasPendingFine = Number(finesStats?.totalPending ?? 0) > 0;
          const hasActiveFine = Number(finesStats?.totalActive ?? 0) > 0;
          const hasPendingObligation = Number(obligationStats?.totalPending ?? 0) > 0;
          const hasOverdueObligation = Number(obligationStats?.totalOverdue ?? 0) > 0;
          const shouldShow =
            isWalletFrozen ||
            hasPendingFine ||
            hasActiveFine ||
            hasPendingObligation ||
            hasOverdueObligation;
          if (!shouldShow) return null;
          return (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <LockKeyhole className="h-4 w-4" /> Payment Required
                </CardTitle>
                <CardDescription className="mt-1">
                  Clear pending obligations to restore full access to your account.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                {loading ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <Skeleton key={i} className="h-5 w-full" />
                  ))
                ) : (
                  <>
                    {isWalletFrozen && (
                      <div className="flex items-center justify-between rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2.5">
                        <span className="text-sm font-medium text-red-700 dark:text-red-300">Wallet Status</span>
                        <Badge variant="danger">FROZEN</Badge>
                      </div>
                    )}

                    {(hasPendingFine || hasActiveFine) && (
                      <div className="space-y-2">
                        <p className="text-xs font-medium uppercase tracking-wide text-ink-faint">Fines</p>
                        {hasPendingFine && (
                          <InfoRow label="Pending" value={formatCurrency(finesStats!.totalPending)} />
                        )}
                        {hasActiveFine && (
                          <InfoRow label="Active" value={formatCurrency(finesStats!.totalActive)} />
                        )}
                      </div>
                    )}

                    {(hasPendingObligation || hasOverdueObligation) && (
                      <div className="space-y-2">
                        <p className="text-xs font-medium uppercase tracking-wide text-ink-faint">Obligations</p>
                        {hasPendingObligation && (
                          <InfoRow label="Pending" value={formatCurrency(obligationStats!.totalPending)} />
                        )}
                        {hasOverdueObligation && (
                          <InfoRow label="Overdue" value={formatCurrency(obligationStats!.totalOverdue)} />
                        )}
                      </div>
                    )}
                  </>
                )}
              </CardContent>
            </Card>
          );
        })()}
      </div>
    </div>
  );
}

function StatusRow({ label, ok }: { label: string; ok: boolean }) {
  return (
    <div className="flex items-center justify-between rounded-xl border border-line bg-surface-raised px-3 py-2.5">
      <span className="text-sm text-ink-muted">{label}</span>
      <span className={`flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium ${
        ok ? 'bg-emerald-500/10 text-emerald-600' : 'bg-amber-500/10 text-amber-600'
      }`}>
        <span className={`h-1.5 w-1.5 rounded-full ${ok ? 'bg-emerald-500' : 'bg-amber-500'}`} />
        {ok ? 'Enabled' : 'Not set'}
      </span>
    </div>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between rounded-xl border border-line bg-surface-raised px-3 py-2.5">
      <span className="text-sm text-ink-muted">{label}</span>
      <span className="text-sm font-medium text-ink">{value}</span>
    </div>
  );
}

function QuickActionItem({ href, icon: Icon, label, desc }: { href: string; icon: typeof ArrowDownLeft; label: string; desc: string }) {
  return (
    <Link
      href={href}
      className="group flex items-center gap-3 rounded-xl border border-transparent p-2.5 transition-all hover:border-line hover:bg-surface-raised"
    >
      <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-surface-raised text-ink-muted transition-colors group-hover:bg-primary-500/10 group-hover:text-primary-600">
        <Icon className="h-4 w-4" />
      </div>
      <div className="min-w-0 flex-1">
        <p className="text-sm font-medium text-ink">{label}</p>
        <p className="truncate text-xs text-ink-faint">{desc}</p>
      </div>
      <ExternalArrow className="h-4 w-4 text-ink-faint transition-transform group-hover:translate-x-0.5 group-hover:text-ink-muted" />
    </Link>
  );
}
