'use client';

import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useAuth } from '@/hooks/useAuth';
import { FileText, CreditCard, Clock, CheckCircle, XCircle, Gift, Sparkles, Wallet } from 'lucide-react';
import { useState, useEffect } from 'react';
import api from '@/lib/api';

// Helper function to calculate hours until midnight
function getHoursUntilMidnight(): number {
  const now = new Date();
  const midnight = new Date(now);
  midnight.setHours(24, 0, 0, 0);
  return Math.ceil((midnight.getTime() - now.getTime()) / (1000 * 60 * 60));
}

export default function DashboardPage() {
  const { user } = useAuth();
  const [hoursUntilReset, setHoursUntilReset] = useState(getHoursUntilMidnight());
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Fetch orders on mount
  useEffect(() => {
    const fetchOrders = async () => {
      try {
        setLoading(true);
        const data = await api.getOrders();
        setOrders(data.orders || []);
      } catch (error) {
        console.error('Failed to fetch orders:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchOrders();
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      setHoursUntilReset(getHoursUntilMidnight());
    }, 60000);
    return () => clearInterval(timer);
  }, []);

  // Calculate stats from real orders
  const stats = {
    totalOrders: orders.length,
    completedOrders: orders.filter(o => o.status === 'Completed').length,
    pendingOrders: orders.filter(o => ['Processing', 'AI Translating', 'Pending Payment'].includes(o.status)).length,
    failedOrders: orders.filter(o => o.status === 'Failed').length,
  };

  // Get 5 most recent orders
  const recentOrders = orders.slice(0, 5);

  return (
    <div className="p-6 lg:p-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-gray-600 mt-1">
          Welcome back, {user?.Name || 'User'}!
        </p>
      </div>

      {/* Credit Balance Cards - 3 Types */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {/* Credit Balance */}
        <Card className="bg-gradient-to-br from-blue-500 to-blue-600 text-white">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center gap-2">
              <Wallet className="h-4 w-4" />
              Credit Balance
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-3xl font-bold">
              {(user?.credits_balance || user?.['Credits Balance'] || user?.['Purchased Credits'] || 0).toLocaleString()}
            </p>
            <p className="text-blue-100 text-xs mt-1">Includes signup bonus</p>
          </CardContent>
        </Card>

        {/* Daily Free Credits */}
        <Card className="bg-gradient-to-br from-orange-400 to-orange-500 text-white">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center gap-2">
              <Gift className="h-4 w-4" />
              Daily Free Credits
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-3xl font-bold">
              {user?.daily_free_credits || user?.['Daily Free Credits'] || user?.['Free Credits Daily'] || 10}
            </p>
            <p className="text-orange-100 text-xs mt-1">Expires in {hoursUntilReset}h</p>
          </CardContent>
        </Card>

        {/* Bonus Credits */}
        <Card className="bg-gradient-to-br from-green-500 to-green-600 text-white">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-sm flex items-center gap-2">
              <Sparkles className="h-4 w-4" />
              Bonus Credits
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-3xl font-bold">
              {(user?.bonus_credits || user?.['Bonus Credits'] || 0).toLocaleString()}
            </p>
            <p className="text-green-100 text-xs mt-1">From referrals & achievements</p>
          </CardContent>
        </Card>
      </div>

      {/* Total Credits Summary */}
      <Card className="mb-8 border-2 border-gray-200">
        <CardContent className="py-4">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <CreditCard className="h-8 w-8 text-blue-600" />
              <div>
                <p className="text-sm text-gray-500">Total Available</p>
                <p className="text-2xl font-bold text-gray-900">
                  {(
                    (user?.credits_balance || user?.['Credits Balance'] || 0) +
                    (user?.daily_free_credits || user?.['Daily Free Credits'] || user?.['Free Credits Daily'] || 10) +
                    (user?.bonus_credits || user?.['Bonus Credits'] || 0)
                  ).toLocaleString()} credits
                </p>
              </div>
            </div>
            <Link href="/dashboard/credits">
              <Button size="lg">
                Buy Credits
              </Button>
            </Link>
          </div>
        </CardContent>
      </Card>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">
              Total Orders
            </CardTitle>
            <FileText className="h-4 w-4 text-gray-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalOrders}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">
              Completed
            </CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {stats.completedOrders}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">
              In Progress
            </CardTitle>
            <Clock className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {stats.pendingOrders}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">
              Failed
            </CardTitle>
            <XCircle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">
              {stats.failedOrders}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle>Quick Actions</CardTitle>
          <CardDescription>Get started with common tasks</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Link href="/dashboard/orders/new" className="block">
              <Button className="w-full h-20 text-lg" size="lg">
                <FileText className="mr-2 h-5 w-5" />
                New Translation Order
              </Button>
            </Link>
            <Link href="/dashboard/credits" className="block">
              <Button variant="outline" className="w-full h-20 text-lg" size="lg">
                <CreditCard className="mr-2 h-5 w-5" />
                Purchase Credits
              </Button>
            </Link>
          </div>
        </CardContent>
      </Card>

      {/* Recent Orders */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Recent Orders</CardTitle>
              <CardDescription>Your latest translation requests</CardDescription>
            </div>
            <Link href="/dashboard/orders">
              <Button variant="outline">View All</Button>
            </Link>
          </div>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="text-center py-12">
              <div className="animate-spin h-8 w-8 border-4 border-blue-600 border-t-transparent rounded-full mx-auto"></div>
              <p className="text-gray-600 mt-4">Loading orders...</p>
            </div>
          ) : recentOrders.length === 0 ? (
            <div className="text-center py-12">
              <FileText className="h-12 w-12 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                No orders yet
              </h3>
              <p className="text-gray-600 mb-6">
                Get started by creating your first translation order
              </p>
              <Link href="/dashboard/orders/new">
                <Button>Create Order</Button>
              </Link>
            </div>
          ) : (
            <div className="space-y-4">
              {recentOrders.map((order: any) => {
                const statusColors: Record<string, string> = {
                  'Completed': 'bg-green-100 text-green-700',
                  'Processing': 'bg-blue-100 text-blue-700',
                  'AI Translating': 'bg-purple-100 text-purple-700',
                  'Failed': 'bg-red-100 text-red-700',
                  'Pending Payment': 'bg-yellow-100 text-yellow-700',
                };

                return (
                  <Link
                    key={order.id || order.order_id}
                    href={`/dashboard/orders/${order.order_id}`}
                    className="block"
                  >
                    <div className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors">
                      <div className="flex-1">
                        <p className="font-medium">{order.order_name || order.order_id}</p>
                        <p className="text-sm text-gray-600">
                          {order.source_language} → {order.target_language}
                        </p>
                      </div>
                      <div className="text-right">
                        <span className={`inline-block px-2 py-1 text-xs rounded-full ${statusColors[order.status] || 'bg-gray-100 text-gray-700'}`}>
                          {order.status}
                        </span>
                        <p className="text-sm text-gray-600 mt-1">
                          {new Date(order.created_at).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                  </Link>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
