"use client";
import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { 
  BarChart3, 
  FileImage, 
  TrendingDown, 
  Clock,
  Download,
  Settings,
  Zap,
  CheckCircle,
  Loader,
  XCircle
} from 'lucide-react';

import { dashboardApi } from '@/app/api/api';

interface BatchHistory {
  id: string;
  name: string;
  total_files: number;
  completed_files: number;
  total_original_size: number;
  total_optimized_size: number;
  status: string;
  created_at: string;
  download_url?: string;
}

interface UserStats {
  images_processed_this_month: number;
  total_images_processed: number;
  monthly_image_limit: number;
  subscription_tier: string;
}

export default function DashboardPage (){

  const { user } = useAuth();
  const [stats, setStats] = useState<UserStats | null>(null);
  const [batches, setBatches] = useState<BatchHistory[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (user) {
      loadDashboardData();
    }
  }, [user]);

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      const [userStats, batchHistory] = await Promise.all([
        dashboardApi.getUserStats(),
        dashboardApi.getBatchHistory()
      ]);
      setStats(userStats);
      setBatches(batchHistory);
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const calculateSavings = (original: number, optimized: number) => {
    if (optimized === 0 || original === 0) return 0;
    return Math.round(((original - optimized) / original) * 100);
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded mb-4 w-1/3"></div>
          <div className="grid md:grid-cols-3 gap-6 mb-8">
            {[1, 2, 3].map(i => (
              <div key={i} className="bg-gray-200 h-32 rounded-2xl"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  const usagePercentage = stats ? (stats.images_processed_this_month / stats.monthly_image_limit) * 100 : 0;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">
          Welcome back, {user?.name}!
        </h1>
        <p className="text-gray-600">
          Here's an overview of your image optimization activity.
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid md:grid-cols-3 gap-6 mb-8">
        <div className="bg-gradient-to-br from-blue-50 to-blue-100 p-6 rounded-2xl">
          <div className="flex items-center justify-between mb-4">
            <div className="bg-blue-500 w-12 h-12 rounded-lg flex items-center justify-center">
              <FileImage className="w-6 h-6 text-white" />
            </div>
            <span className={`px-3 py-1 rounded-full text-xs font-medium ${
              stats?.subscription_tier === 'free' ? 'bg-gray-100 text-gray-800' :
              stats?.subscription_tier === 'pro' ? 'bg-blue-100 text-blue-800' :
              'bg-purple-100 text-purple-800'
            }`}>
              {stats?.subscription_tier?.toUpperCase()}
            </span>
          </div>
          <h3 className="text-2xl font-bold text-gray-900">
            {stats?.images_processed_this_month || 0}
          </h3>
          <p className="text-gray-600 text-sm">
            of {stats?.monthly_image_limit || 0} images this month
          </p>
          <div className="mt-3">
            <div className="w-full bg-blue-200 rounded-full h-2">
              <div 
                className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                style={{ width: `${Math.min(100, usagePercentage)}%` }}
              />
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-br from-green-50 to-green-100 p-6 rounded-2xl">
          <div className="bg-green-500 w-12 h-12 rounded-lg flex items-center justify-center mb-4">
            <TrendingDown className="w-6 h-6 text-white" />
          </div>
          <h3 className="text-2xl font-bold text-gray-900">
            {batches.reduce((total, batch) => 
              total + calculateSavings(batch.total_original_size, batch.total_optimized_size), 0
            ) / Math.max(1, batches.length)}%
          </h3>
          <p className="text-gray-600 text-sm">Average file size reduction</p>
        </div>

        <div className="bg-gradient-to-br from-purple-50 to-purple-100 p-6 rounded-2xl">
          <div className="bg-purple-500 w-12 h-12 rounded-lg flex items-center justify-center mb-4">
            <Zap className="w-6 h-6 text-white" />
          </div>
          <h3 className="text-2xl font-bold text-gray-900">
            {stats?.total_images_processed || 0}
          </h3>
          <p className="text-gray-600 text-sm">Total images optimized</p>
        </div>
      </div>

      {/* Recent Activity */}
      <div className="bg-white rounded-2xl shadow-lg p-8">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-900">Recent Activity</h2>
          <button className="text-blue-600 hover:text-blue-700 text-sm font-medium">
            View All
          </button>
        </div>

        {batches.length === 0 ? (
          <div className="text-center py-12">
            <BarChart3 className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500 mb-2">No processing history yet</p>
            <p className="text-sm text-gray-400">
              Start optimizing images to see your activity here
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {batches.slice(0, 5).map((batch) => (
              <div key={batch.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                <div className="flex items-center space-x-4">
                  <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                    batch.status === 'completed' ? 'bg-green-100' :
                    batch.status === 'processing' ? 'bg-blue-100' :
                    batch.status === 'failed' ? 'bg-red-100' : 'bg-yellow-100'
                  }`}>
                    {batch.status === 'completed' ? <CheckCircle className="w-5 h-5 text-green-600" /> :
                     batch.status === 'processing' ? <Loader className="w-5 h-5 text-blue-600 animate-spin" /> :
                     batch.status === 'failed' ? <XCircle className="w-5 h-5 text-red-600" /> :
                     <Clock className="w-5 h-5 text-yellow-600" />}
                  </div>
                  <div>
                    <p className="font-medium text-gray-900">{batch.name}</p>
                    <p className="text-sm text-gray-600">
                      {batch.completed_files}/{batch.total_files} files • {formatFileSize(batch.total_original_size)}
                      {batch.status === 'completed' && batch.total_optimized_size > 0 && (
                        <span className="text-green-600 ml-2">
                          → {formatFileSize(batch.total_optimized_size)} 
                          ({calculateSavings(batch.total_original_size, batch.total_optimized_size)}% saved)
                        </span>
                      )}
                    </p>
                  </div>
                </div>
                <div className="flex items-center space-x-3">
                  <span className="text-xs text-gray-500">
                    {new Date(batch.created_at).toLocaleDateString()}
                  </span>
                  {batch.status === 'completed' && batch.download_url && (
                    <button className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
                      <Download className="w-4 h-4" />
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}