import { useState, useEffect } from 'react'
import { 
  Users, 
  TrendingUp, 
  FileText, 
  Activity,
  Building2,
  DollarSign,
  BarChart3,
  PieChart,
  RefreshCw,
  Download,
  Eye,
  Calendar,
  Filter,
  MoreVertical,
  Plus,
  ArrowUpRight,
  ArrowDownRight,
  MapPin,
  Home,
  Briefcase,
  TrendingDown,
  AlertCircle,
  CheckCircle,
  Clock
} from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { analyticsAPI, monitoringAPI, reportsAPI } from '../services/api'
import StatCard from '../components/StatCard'
import Chart from '../components/Chart'
import RecentActivity from '../components/RecentActivity'
import toast from 'react-hot-toast'

const Dashboard = () => {
  const [timeRange, setTimeRange] = useState('90d')
  const [refreshing, setRefreshing] = useState(false)

  // Fetch dashboard data
  const { data: metrics, isLoading: metricsLoading, refetch: refetchMetrics } = useQuery({
    queryKey: ['metrics'],
    queryFn: monitoringAPI.getMetrics,
    placeholderData: {
      total_users: 2,
      active_sessions: 1,
      api_calls_today: 0,
      reports_generated: 0,
      system_health: 'healthy'
    },
  })

  const { data: transactionSummary, isLoading: summaryLoading, refetch: refetchSummary } = useQuery({
    queryKey: ['transactionSummary', timeRange],
    queryFn: () => analyticsAPI.getTransactionSummary({ 
      start_date: getDateRange(timeRange).start,
      end_date: getDateRange(timeRange).end 
    }),
    placeholderData: {
      total_transactions: 1,
      total_value: 0,
      average_value: 0,
      growth_rate: 0
    },
  })

  const { data: timeSeriesData, isLoading: timeSeriesLoading, refetch: refetchTimeSeries } = useQuery({
    queryKey: ['timeSeriesData', timeRange],
    queryFn: () => analyticsAPI.getTimeSeriesData({ 
      start_date: getDateRange(timeRange).start,
      end_date: getDateRange(timeRange).end,
      group_by: 'day'
    }),
    placeholderData: [],
    retry: 3,
    retryDelay: 1000,
  })

  const { data: areaStats, isLoading: areaStatsLoading, refetch: refetchAreaStats } = useQuery({
    queryKey: ['areaStats', timeRange],
    queryFn: () => analyticsAPI.getAreaStats({ 
      start_date: getDateRange(timeRange).start,
      end_date: getDateRange(timeRange).end,
      limit: 5
    }),
    placeholderData: [],
    retry: 3,
    retryDelay: 1000,
  })

  // Process chart data
  const processedTimeSeriesData = timeSeriesData && Array.isArray(timeSeriesData) && timeSeriesData.length > 0 ? {
    labels: timeSeriesData.map(item => new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })),
    datasets: [
      {
        label: 'Transactions',
        data: timeSeriesData.map(item => item.transactions),
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.4,
        fill: true,
      },
      {
        label: 'Value (AED)',
        data: timeSeriesData.map(item => item.value / 1000000), // Convert to millions
        borderColor: 'rgb(16, 185, 129)',
        backgroundColor: 'rgba(16, 185, 129, 0.1)',
        tension: 0.4,
        fill: true,
        yAxisID: 'y1',
      }
    ]
  } : null

  const processedAreaStatsData = areaStats && Array.isArray(areaStats) && areaStats.length > 0 ? {
    labels: areaStats.map(item => item.area_en),
    datasets: [
      {
        label: 'Transaction Count',
        data: areaStats.map(item => item.transaction_count),
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(16, 185, 129, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)',
          'rgba(16, 185, 129, 0.8)',
        ],
        borderColor: [
          'rgb(59, 130, 246)',
          'rgb(16, 185, 129)',
          'rgb(245, 158, 11)',
          'rgb(239, 68, 68)',
          'rgb(16, 185, 129)',
        ],
        borderWidth: 2,
      }
    ]
  } : null

  const { data: reports, isLoading: reportsLoading, refetch: refetchReports } = useQuery({
    queryKey: ['reports'],
    queryFn: reportsAPI.getReports,
    placeholderData: [],
  })

  // Additional data queries for sample data analytics
  const { data: brokerStats, isLoading: brokerStatsLoading, error: brokerStatsError } = useQuery({
    queryKey: ['brokerStats'],
    queryFn: () => analyticsAPI.getBrokerStats(),
    retry: 1,
  })

  const { data: projectStats, isLoading: projectStatsLoading, error: projectStatsError } = useQuery({
    queryKey: ['projectStats'],
    queryFn: () => analyticsAPI.getProjectStats(),
    retry: 1,
  })

  const { data: landStats, isLoading: landStatsLoading, error: landStatsError } = useQuery({
    queryKey: ['landStats'],
    queryFn: () => analyticsAPI.getLandStats(),
    retry: 1,
  })

  const { data: valuationStats, isLoading: valuationStatsLoading, error: valuationStatsError } = useQuery({
    queryKey: ['valuationStats'],
    queryFn: () => analyticsAPI.getValuationStats(),
    retry: 1,
  })

  const { data: rentStats, isLoading: rentStatsLoading, error: rentStatsError } = useQuery({
    queryKey: ['rentStats'],
    queryFn: () => analyticsAPI.getRentStats(),
    retry: 1,
  })


  function getDateRange(range) {
    const now = new Date()
    const start = new Date()
    
    switch (range) {
      case '7d':
        start.setDate(now.getDate() - 7)
        break
      case '30d':
        start.setDate(now.getDate() - 30)
        break
      case '90d':
        start.setDate(now.getDate() - 90)
        break
      case '1y':
        start.setDate(now.getDate() - 365)
        break
      case 'all':
        // Set to a very early date for "all time"
        start.setFullYear(2020, 0, 1)
        break
      default:
        start.setDate(now.getDate() - 90)
    }
    
    return {
      start: start.toISOString().split('T')[0],
      end: now.toISOString().split('T')[0]
    }
  }

  const handleRefresh = async () => {
    setRefreshing(true)
    try {
      await Promise.all([
        refetchMetrics(),
        refetchSummary(),
        refetchTimeSeries(),
        refetchAreaStats(),
        refetchReports()
      ])
      toast.success('Dashboard refreshed successfully')
    } catch (error) {
      toast.error('Failed to refresh dashboard')
    } finally {
      setRefreshing(false)
    }
  }

  const handleGenerateReport = async (type) => {
    try {
      const reportData = {
        area: '',
        property_type: '',
        start_date: getDateRange(timeRange).start,
        end_date: getDateRange(timeRange).end,
        format: 'pdf'
      }
      
      let response
      switch (type) {
        case 'transaction_summary':
          response = await reportsAPI.generateTransactionSummary(reportData)
          break
        case 'area_analysis':
          response = await reportsAPI.generateAreaAnalysis(reportData)
          break
        default:
          response = await reportsAPI.generateForecast(reportData)
      }
      
      if (response.data) {
        toast.success('Report generation started')
        refetchReports()
      }
    } catch (error) {
      toast.error('Failed to generate report')
    }
  }

  // Dynamic stats based on actual data
  const stats = [
    {
      title: 'Total Brokers',
      value: brokerStats ? 
        (() => {
          const total = brokerStats.gender_distribution?.reduce((sum, item) => sum + item.count, 0)
          return typeof total === 'number' ? total.toLocaleString() : '0'
        })() 
        : '...',
      change: brokerStats?.gender_distribution?.find(item => item.gender === 'male')?.count ? 
        `${Math.round((brokerStats.gender_distribution.find(item => item.gender === 'male').count / brokerStats.gender_distribution.reduce((sum, item) => sum + item.count, 0)) * 100)}% male` 
        : '0%',
      changeType: 'neutral',
      icon: Briefcase,
      color: 'blue',
      loading: brokerStatsLoading,
      trend: '0%',
      trendIcon: TrendingUp
    },
    {
      title: 'Active Projects',
      value: projectStats ? 
        (() => {
          const count = projectStats.status_distribution?.find(item => item.project_status === 'ACTIVE')?.count
          return typeof count === 'number' ? count.toLocaleString() : '0'
        })() 
        : '...',
      change: projectStats?.status_distribution?.length ? 
        `${projectStats.status_distribution.length} status types` 
        : '0',
      changeType: 'positive',
      icon: Building2,
      color: 'green',
      loading: projectStatsLoading,
      trend: '0%',
      trendIcon: ArrowUpRight
    },
    {
      title: 'Total Lands',
      value: landStats ? 
        (() => {
          const total = landStats.type_distribution?.reduce((sum, item) => sum + item.count, 0)
          return typeof total === 'number' ? total.toLocaleString() : '0'
        })() 
        : '...',
      change: landStats?.type_distribution?.length ? 
        `${landStats.type_distribution.length} land types` 
        : '0',
      changeType: 'positive',
      icon: MapPin,
      color: 'purple',
      loading: landStatsLoading,
      trend: '0%',
      trendIcon: TrendingUp
    },
    {
      title: 'System Health',
      value: metrics?.system_health === 'healthy' ? '100%' : '95%',
      change: '+5%',
      changeType: 'positive',
      icon: Activity,
      color: 'yellow',
      loading: metricsLoading,
      trend: '+5%',
      trendIcon: ArrowUpRight
    }
  ]

  return (
    <div className="space-y-8 animate-fade-in">
      {/* Header */}
      <div className="bg-gradient-to-r from-slate-800 via-slate-700 to-slate-600 rounded-2xl p-8 text-white shadow-2xl">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold mb-2 tracking-tight">
              Dubai Analytics Dashboard
            </h1>
            <p className="text-slate-200 text-base font-normal">
              Real-time insights into Dubai's real estate market
            </p>
            <div className="flex items-center mt-4 space-x-6">
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-5 w-5 text-green-300" />
                <span className="text-sm font-medium">System Online</span>
              </div>
              <div className="flex items-center space-x-2">
                <Clock className="h-5 w-5 text-slate-300" />
                <span className="text-sm font-medium">Last updated: {new Date().toLocaleTimeString()}</span>
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2 bg-slate-700/50 backdrop-blur-sm rounded-lg px-4 py-2 border border-slate-600">
              <Calendar className="h-4 w-4 text-slate-300" />
              <select
                value={timeRange}
                onChange={(e) => setTimeRange(e.target.value)}
                className="bg-transparent text-white border-none outline-none cursor-pointer"
              >
                <option value="7d" className="text-gray-900 bg-white">Last 7 days</option>
                <option value="30d" className="text-gray-900 bg-white">Last 30 days</option>
                <option value="90d" className="text-gray-900 bg-white">Last 90 days</option>
                <option value="1y" className="text-gray-900 bg-white">Last year</option>
                <option value="all" className="text-gray-900 bg-white">All time</option>
              </select>
            </div>
            
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="bg-slate-700/50 backdrop-blur-sm hover:bg-slate-600/50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 rounded-lg px-4 py-2 flex items-center space-x-2 border border-slate-600"
            >
              <RefreshCw className={`h-4 w-4 text-slate-300 ${refreshing ? 'animate-spin' : ''}`} />
              <span className="text-slate-300">Refresh</span>
            </button>
            
            <div className="relative">
              <button className="bg-slate-600 text-white hover:bg-slate-500 transition-all duration-200 rounded-lg px-4 py-2 font-medium flex items-center space-x-2 text-sm border border-slate-500">
                <Plus className="h-4 w-4" />
                <span>Quick Actions</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {stats.map((stat, index) => (
          <StatCard key={index} {...stat} />
        ))}
      </div>




      {/* Sample Data Analytics Charts */}
      <div className="space-y-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <BarChart3 className="h-5 w-5 mr-2 text-blue-500" />
                Transaction Volume by Area
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {areaStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              </div>
            ) : areaStats && areaStats.length > 0 ? (
              <Chart
                data={areaStats}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <BarChart3 className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No area data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <TrendingUp className="h-5 w-5 mr-2 text-green-500" />
                Transaction Trends
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {timeSeriesLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
              </div>
            ) : timeSeriesData && timeSeriesData.length > 0 ? (
              <Chart
                data={timeSeriesData}
                type="line"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <TrendingUp className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No trend data available</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Brokers Analysis */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <Users className="h-5 w-5 mr-2 text-purple-500" />
                Broker Gender Distribution
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {brokerStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
              </div>
            ) : brokerStatsError ? (
              <div className="flex items-center justify-center h-64 text-red-500">
                <div className="text-center">
                  <p>Error: {brokerStatsError.message}</p>
                </div>
              </div>
            ) : brokerStats && brokerStats.gender_distribution && brokerStats.gender_distribution.length > 0 ? (
              <Chart
                data={brokerStats.gender_distribution.map(item => ({
                  area: item.gender,
                  transaction_count: item.count
                }))}
                type="pie"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <Users className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No broker data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <Building2 className="h-5 w-5 mr-2 text-orange-500" />
                Top Real Estate Companies
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {brokerStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-500"></div>
              </div>
            ) : brokerStats && brokerStats.top_companies && brokerStats.top_companies.length > 0 ? (
              <Chart
                data={brokerStats.top_companies.map(item => ({
                  area: item.real_estate_name_en,
                  transaction_count: item.broker_count
                }))}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <Building2 className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No company data available</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Projects Analysis */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <Activity className="h-5 w-5 mr-2 text-red-500" />
                Project Status Distribution
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {projectStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-500"></div>
              </div>
            ) : projectStats && projectStats.status_distribution && projectStats.status_distribution.length > 0 ? (
              <Chart
                data={projectStats.status_distribution.map(item => ({
                  area: item.project_status,
                  transaction_count: item.count
                }))}
                type="pie"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <Activity className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No project data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <TrendingUp className="h-5 w-5 mr-2 text-indigo-500" />
                Project Completion Rates
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {projectStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-500"></div>
              </div>
            ) : projectStats && projectStats.completion_rates && projectStats.completion_rates.length > 0 ? (
              <Chart
                data={projectStats.completion_rates.map(item => ({
                  area: item.range,
                  transaction_count: item.count
                }))}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <TrendingUp className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No completion data available</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Lands Analysis */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <MapPin className="h-5 w-5 mr-2 text-green-500" />
                Land Type Distribution
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {landStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
              </div>
            ) : landStats && landStats.type_distribution && landStats.type_distribution.length > 0 ? (
              <Chart
                data={landStats.type_distribution.map(item => ({
                  area: item.land_type,
                  transaction_count: item.count
                }))}
                type="pie"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <MapPin className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No land data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <Building2 className="h-5 w-5 mr-2 text-blue-500" />
                Top Areas by Land Count
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {landStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              </div>
            ) : landStats && landStats.area_distribution && landStats.area_distribution.length > 0 ? (
              <Chart
                data={landStats.area_distribution.map(item => ({
                  area: item.area_en,
                  transaction_count: item.land_count
                }))}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <Building2 className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No area data available</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Valuations Analysis */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <DollarSign className="h-5 w-5 mr-2 text-yellow-500" />
                Property Value Trends
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {valuationStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-yellow-500"></div>
              </div>
            ) : valuationStats && valuationStats.value_trends && valuationStats.value_trends.length > 0 ? (
              <Chart
                data={valuationStats.value_trends.map(item => ({
                  date: item.month,
                  value: item.avg_value
                }))}
                type="line"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <DollarSign className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No valuation data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <MapPin className="h-5 w-5 mr-2 text-purple-500" />
                Top Valued Areas
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {valuationStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
              </div>
            ) : valuationStats && valuationStats.top_valued_areas && valuationStats.top_valued_areas.length > 0 ? (
              <Chart
                data={valuationStats.top_valued_areas.map(item => ({
                  area: item.area_en,
                  transaction_count: Math.round(item.avg_value / 1000000) // Convert to millions for display
                }))}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <MapPin className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No area valuation data available</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Rents Analysis */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <Home className="h-5 w-5 mr-2 text-cyan-500" />
                Rental Property Types
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {rentStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
              </div>
            ) : rentStats && rentStats.property_types && rentStats.property_types.length > 0 ? (
              <Chart
                data={rentStats.property_types.map(item => ({
                  area: item.property_type,
                  transaction_count: item.count
                }))}
                type="pie"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <Home className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No rental data available</p>
                </div>
              </div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                <TrendingUp className="h-5 w-5 mr-2 text-pink-500" />
                Average Rental Prices by Area
              </h3>
              <div className="flex space-x-2">
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <RefreshCw className="h-4 w-4" />
                </button>
                <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                  <Download className="h-4 w-4" />
                </button>
              </div>
            </div>
            {rentStatsLoading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-500"></div>
              </div>
            ) : rentStats && rentStats.area_prices && rentStats.area_prices.length > 0 ? (
              <Chart
                data={rentStats.area_prices.map(item => ({
                  area: item.area_en,
                  transaction_count: Math.round(item.avg_rent / 1000) // Convert to thousands for display
                }))}
                type="bar"
                height={300}
              />
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500 dark:text-gray-400">
                <div className="text-center">
                  <TrendingUp className="h-12 w-12 mx-auto mb-2 opacity-50" />
                  <p>No rental price data available</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Bottom Row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Recent Activity */}
        <div className="lg:col-span-2">
          <RecentActivity />
        </div>

        {/* Quick Actions & System Status */}
        <div className="space-y-6">
          {/* Quick Actions */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
              Quick Actions
            </h3>
            <div className="space-y-4">
              <button 
                onClick={() => handleGenerateReport('transaction_summary')}
                className="w-full bg-gradient-to-r from-slate-600 to-slate-700 hover:from-slate-700 hover:to-slate-800 text-white font-medium py-2 px-3 rounded-lg transition-all duration-200 flex items-center justify-center space-x-2 shadow-lg hover:shadow-xl text-sm"
              >
                <FileText className="h-4 w-4" />
                <span>Generate Report</span>
              </button>
              <button className="w-full bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium py-2 px-3 rounded-lg transition-all duration-200 flex items-center justify-center space-x-2 text-sm">
                <Eye className="h-4 w-4" />
                <span>View Analytics</span>
              </button>
              <button className="w-full bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium py-2 px-3 rounded-lg transition-all duration-200 flex items-center justify-center space-x-2 text-sm">
                <Users className="h-4 w-4" />
                <span>Manage Users</span>
              </button>
              <button className="w-full bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium py-2 px-3 rounded-lg transition-all duration-200 flex items-center justify-center space-x-2 text-sm">
                <Activity className="h-4 w-4" />
                <span>System Settings</span>
              </button>
            </div>
          </div>

          {/* System Status */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] hover:border-blue-300 dark:hover:border-blue-600">
            <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-6">
              System Status
            </h3>
            <div className="space-y-4">
              <div className="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">API Status</span>
                </div>
                <span className="text-sm font-semibold text-green-600 dark:text-green-400">Online</span>
              </div>
              <div className="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">Database</span>
                </div>
                <span className="text-sm font-semibold text-green-600 dark:text-green-400">Connected</span>
              </div>
              <div className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-900/20 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 bg-slate-500 rounded-full"></div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">Last Update</span>
                </div>
                <span className="text-sm font-semibold text-slate-600 dark:text-slate-400">
                  {new Date().toLocaleTimeString()}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 bg-purple-500 rounded-full"></div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">Data Records</span>
                </div>
                <span className="text-sm font-semibold text-purple-600 dark:text-purple-400">500,000+</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Dashboard

