'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useStore } from '@/lib/store';
import { walletApi, transactionApi, overseerApi } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  Wallet, 
  TrendingUp, 
  TrendingDown, 
  Clock, 
  Film,
  ExternalLink,
  Plus,
  History
} from 'lucide-react';
import { formatNumber, truncateAddress } from '@/lib/utils';
import { toast } from 'sonner';
import { useSocket } from '@/lib/socket';
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui';
import { TransactionList } from './components/TransactionList';
import { WatchHistory } from './components/WatchHistory';
import { CreateWalletModal } from './components/CreateWalletModal';
import { WelcomeOnboarding } from './components/WelcomeOnboarding';
import { ActivityFeed } from './components/ActivityFeed';
import { SearchRequestModal } from './components/SearchRequestModal';
import { RequestHistory } from './components/RequestHistory';
import { Leaderboard } from './components/Leaderboard';

interface WalletData {
  hasWallet: boolean;
  address?: string;
  balance: number;
  totalEarned: number;
  totalSpent: number;
  explorerUrl?: string;
}

export default function DashboardPage() {
  const router = useRouter();
  const { user, isAuthenticated, logout } = useStore();
  const [wallet, setWallet] = useState<WalletData | null>(null);
  const [requestCosts, setRequestCosts] = useState({ movie: 100, tv: 200 });
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const socket = useSocket();

  useEffect(() => {
    if (!isAuthenticated) {
      router.push('/login');
      return;
    }

    loadData();
  }, [isAuthenticated, router]);

  useEffect(() => {
    if (socket) {
      socket.on('credits_earned', (data) => {
        toast.success(`You earned ${data.amount} $COOP!`, {
          description: `Watched: ${data.title}`,
        });
        loadData();
      });

      socket.on('bonus_received', (data) => {
        toast.success(`Bonus Received: ${data.amount} $COOP!`, {
          description: data.reason,
        });
        loadData();
      });

      socket.on('credits_spent', (data) => {
        toast.info(`Requested: ${data.title}`, {
          description: `Spent ${data.amount} $COOP`,
        });
        loadData();
      });

      return () => {
        socket.off('credits_earned');
        socket.off('bonus_received');
        socket.off('credits_spent');
      };
    }
  }, [socket]);

  const loadData = async () => {
    try {
      const [walletRes, costsRes] = await Promise.all([
        walletApi.getWallet(),
        overseerApi.getCosts().catch(() => ({ data: { movie: 100, tv: 200 } }))
      ]);
      
      setWallet(walletRes.data);
      setRequestCosts(costsRes.data);
    } catch (error) {
      toast.error('Failed to load wallet data');
    } finally {
      setIsLoading(false);
    }
  };

  if (!isAuthenticated || !user) {
    return null;
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card">
        <div className="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <h1 className="text-2xl font-bold">CoopCredits</h1>
            <Badge variant="secondary">{user.plexUsername}</Badge>
            {user.isAdmin && (
              <Button variant="outline" size="sm" onClick={() => router.push('/admin')}>
                Admin
              </Button>
            )}
          </div>
          <div className="flex items-center gap-4">
            <div className="wallet-adapter-custom-wrapper hidden md:block">
              <WalletMultiButton className="!h-9 !px-4 !text-sm !rounded-md !bg-secondary !text-secondary-foreground hover:!bg-secondary/80" />
            </div>
            <Button variant="ghost" onClick={logout}>
              Sign Out
            </Button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 py-8">
        {/* Onboarding for new users */}
        {!wallet?.hasWallet && !isLoading && (
          <WelcomeOnboarding onStart={() => setIsCreateModalOpen(true)} onConnected={loadData} />
        )}

        {/* Stats Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Balance</CardTitle>
              <Wallet className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {wallet ? formatNumber(wallet.balance) : '--'} $COOP
              </div>
              <p className="text-xs text-muted-foreground">
                {wallet?.hasWallet ? 'Ready to spend' : 'Create wallet to start'}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Total Earned</CardTitle>
              <TrendingUp className="h-4 w-4 text-green-500" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {wallet ? formatNumber(wallet.totalEarned) : '--'} $COOP
              </div>
              <p className="text-xs text-muted-foreground">
                From watching content
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Total Spent</CardTitle>
              <TrendingDown className="h-4 w-4 text-red-500" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {wallet ? formatNumber(wallet.totalSpent) : '--'} $COOP
              </div>
              <p className="text-xs text-muted-foreground">
                On content requests
              </p>
            </CardContent>
          </Card>

          <Card className="cursor-pointer hover:border-primary/50 transition-colors group" onClick={() => setIsSearchModalOpen(true)}>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Request Cost</CardTitle>
              <Film className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{requestCosts.movie} $COOP</div>
              <p className="text-xs text-muted-foreground">
                Click to request content
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Wallet Section removed from here if redundant, or kept if we want it to show after creation */}
        {wallet?.hasWallet && (
          <Card className="mb-8">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Wallet className="h-5 w-5" />
                Your Wallet
              </CardTitle>
              <CardDescription>
                Manage your Solana wallet and $COOP tokens
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between p-4 bg-muted rounded-lg">
                <div>
                  <p className="text-sm text-muted-foreground">Address</p>
                  <p className="font-mono font-medium">
                    {truncateAddress(wallet.address!)}
                  </p>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => setIsCreateModalOpen(true)}>
                    <History className="mr-2 h-4 w-4" />
                    Backup
                  </Button>
                  <Button variant="outline" size="sm" asChild>
                    <a href={wallet.explorerUrl} target="_blank" rel="noopener noreferrer">
                      <ExternalLink className="mr-2 h-4 w-4" />
                      Explorer
                    </a>
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Tabs */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            <Tabs defaultValue="transactions" className="space-y-4">
              <TabsList>
                <TabsTrigger value="transactions">Transactions</TabsTrigger>
                <TabsTrigger value="history">Watch History</TabsTrigger>
                <TabsTrigger value="requests">My Requests</TabsTrigger>
              </TabsList>
          
          <TabsContent value="transactions">
            <TransactionList />
          </TabsContent>
          
              <TabsContent value="history">
                <WatchHistory />
              </TabsContent>
              <TabsContent value="requests">
                <RequestHistory />
              </TabsContent>
            </Tabs>
          </div>
          <div className="lg:col-span-1 space-y-8">
            <ActivityFeed />
            <Leaderboard />
          </div>
        </div>
      </main>

      <CreateWalletModal 
        open={isCreateModalOpen} 
        onClose={() => setIsCreateModalOpen(false)}
        onCreated={loadData}
      />
      <SearchRequestModal
        open={isSearchModalOpen}
        onClose={() => setIsSearchModalOpen(false)}
        onRequested={loadData}
        costs={requestCosts}
        balance={wallet?.balance || 0}
      />
    </div>
  );
}
