'use client';

import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { Header } from '@/components/header';
import SendPage from '@/components/send-transfer-server-encrypted';
import { MyTransfers } from '@/components/my-transfers';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Send,
  History,
  Files,
  Download,
  Clock,
  Shield,
} from 'lucide-react';

export default function DashboardPage() {
  const [activeTab, setActiveTab] = useState<'send' | 'transfers' | 'files'>(
    'send'
  );
  const { data: session } = useSession();
  const userName = session?.user?.name || 'friend';

  const [stats, setStats] = useState({
    transfersSent: 0,
    downloads: 0,
    totalFilesSent: 0,
    activeTransfers: 0,
    remainingTransfers: 10,
    loading: true,
  });

  const [usage, setUsage] = useState({
    plan: 'free',
    usedMB: 0,
    remainingMB: 0,
    maxMonthlyMB: 20480,
  });

  useEffect(() => {
    async function fetchStats() {
      try {
        const res = await fetch('/api/stats');
        const data = await res.json();
        setStats({ ...data, loading: false });
      } catch (err) {
        console.error('Failed to fetch stats:', err);
      }
    }

    async function fetchUsage() {
      try {
        const res = await fetch('/api/usage');
        const data = await res.json();
        setUsage(data);
      } catch (err) {
        console.error('Failed to fetch usage:', err);
      }
    }

    fetchStats();
    fetchUsage();
  }, []);

  const usagePercent = (usage.usedMB / usage.maxMonthlyMB) * 100;

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-slate-900 dark:via-slate-800 dark:to-slate-900">
      <Header />

      <main className="container mx-auto px-4 py-8">
        <div className="max-w-7xl mx-auto space-y-8">
          {/* Welcome Section */}
          <div className="text-center space-y-4">
            <h1 className="text-3xl md:text-4xl font-bold text-slate-900 dark:text-slate-100">
              Welcome back, {userName}!
            </h1>
            <p className="text-lg text-slate-600 dark:text-slate-400">
              Manage your file transfers and share files securely
            </p>
          </div>

          {/* Quick Stats */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-white/20 dark:border-slate-700/20">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center">
                    <Send className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
                      {stats.loading ? '...' : stats.transfersSent}
                    </p>
                    <p className="text-xs text-slate-600 dark:text-slate-400">
                      Transfers Sent
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-white/20 dark:border-slate-700/20">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-emerald-600 rounded-lg flex items-center justify-center">
                    <Download className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
                      {stats.loading ? '...' : stats.downloads}
                    </p>
                    <p className="text-xs text-slate-600 dark:text-slate-400">
                      Downloads
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-white/20 dark:border-slate-700/20">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-pink-600 rounded-lg flex items-center justify-center">
                    <Files className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
                      {stats.loading ? '...' : stats.totalFilesSent}
                    </p>
                    <p className="text-xs text-slate-600 dark:text-slate-400">
                      Files Uploaded
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-white/20 dark:border-slate-700/20">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-orange-500 to-red-600 rounded-lg flex items-center justify-center">
                    <Clock className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
                      {stats.loading ? '...' : stats.activeTransfers}
                    </p>
                    <p className="text-xs text-slate-600 dark:text-slate-400">
                      Active Transfers
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Account Status */}
          <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-white/20 dark:border-slate-700/20">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-gradient-to-br from-green-400 to-emerald-600 rounded-full flex items-center justify-center">
                    <Shield className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
                      {usage.plan.charAt(0).toUpperCase() + usage.plan.slice(1)}{' '}
                      Plan
                    </h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400">
                      {stats.loading
                        ? 'Loading usage...'
                        : usage.plan === 'free'
                        ? '2 GB max transfer size'
                        : `${usage.maxMonthlyMB / 1024} GB monthly bandwidth`}
                    </p>
                    {usage.plan === 'free' && (
                      <p className="text-sm text-slate-600 dark:text-slate-400">
                        {stats.remainingTransfers} transfers remaining
                      </p>
                    )}
                    {usage.plan !== 'free' && (
                      <>
                        <Progress value={usagePercent} className="mt-2 h-2" />
                        <p className="text-xs text-gray-500 mt-1">
                          {usage.usedMB} MB used of {usage.maxMonthlyMB} MB
                        </p>
                      </>
                    )}
                  </div>
                </div>
                <div className="flex items-center space-x-3">
                  <Badge className="bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
                    Active
                  </Badge>
                  <button className="text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 font-medium text-sm">
                    Upgrade Plan
                  </button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Main Dashboard */}
          <div className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm rounded-2xl shadow-xl border border-white/20 dark:border-slate-700/20 overflow-hidden">
            <div className="border-b border-slate-200 dark:border-slate-700">
              <nav className="flex space-x-8 px-6">
                <button
                  onClick={() => setActiveTab('send')}
                  className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${
                    activeTab === 'send'
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300'
                  }`}
                >
                  <Send className="w-4 h-4" />
                  <span>Send Transfer</span>
                </button>
                <button
                  onClick={() => setActiveTab('transfers')}
                  className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${
                    activeTab === 'transfers'
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300'
                  }`}
                >
                  <History className="w-4 h-4" />
                  <span>My Transfers</span>
                </button>
                <button
                  onClick={() => setActiveTab('files')}
                  className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${
                    activeTab === 'files'
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300'
                  }`}
                >
                  <Files className="w-4 h-4" />
                  <span>File Manager</span>
                </button>
              </nav>
            </div>

            <div className="p-6">
              {activeTab === 'send' && (
                <SendPage />
              )}
              {activeTab === 'transfers' && <MyTransfers />}
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
