import { useState, useRef } from 'react'
import { useQuery } from '@tanstack/react-query'
import { 
  BarChart3, 
  TrendingUp, 
  MapPin, 
  Building2,
  Filter,
  Download,
  RefreshCw,
  Globe,
  BarChart,
  PieChart,
  Activity,
  Share2,
  Settings,
  Maximize2,
  Calendar,
  Layers
} from 'lucide-react'
import { analyticsAPI } from '../services/api'
import Chart from '../components/Chart'
import StatCard from '../components/StatCard'
import GeographicHeatMap from '../components/GeographicHeatMap'
import TimeSeriesChart from '../components/TimeSeriesChart'
import ComparativeAnalysis from '../components/ComparativeAnalysis'
import ExportSharing from '../components/ExportSharing'

const Analytics = () => {
  const [filters, setFilters] = useState({
    area: '',
    property_type: '',
    start_date: '',
    end_date: '',
  })
  const [activeTab, setActiveTab] = useState('overview')
  const [comparisonItems, setComparisonItems] = useState([])
  const [showExportModal, setShowExportModal] = useState(false)
  const [selectedVisualization, setSelectedVisualization] = useState('all')
  
  // Refs for export functionality
  const chartRefs = useRef({})
  const mapRef = useRef(null)
  const timeSeriesRef = useRef(null)
  const comparisonRef = useRef(null)

  const { data: summary, isLoading: summaryLoading } = useQuery({
    queryKey: ['transactionSummary', filters],
    queryFn: () => analyticsAPI.getTransactionSummary(filters),
  })

  const { data: areaStats, isLoading: areaStatsLoading } = useQuery({
    queryKey: ['areaStats', filters],
    queryFn: () => analyticsAPI.getAreaStats(filters),
  })

  const { data: propertyTypeStats, isLoading: propertyTypeLoading } = useQuery({
    queryKey: ['propertyTypeStats', filters],
    queryFn: () => analyticsAPI.getPropertyTypeStats(filters),
  })

  const { data: timeSeriesData, isLoading: timeSeriesLoading } = useQuery({
    queryKey: ['timeSeriesData', filters],
    queryFn: () => analyticsAPI.getTimeSeriesData({
      ...filters,
      group_by: 'month'
    }),
  })

  const { data: marketAnalysis, isLoading: marketAnalysisLoading } = useQuery({
    queryKey: ['marketAnalysis', filters],
    queryFn: () => analyticsAPI.getMarketAnalysis(filters),
    enabled: !!filters.area && !!filters.property_type,
  })

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }))
  }

  const handleApplyFilters = () => {
    // Filters are automatically applied via React Query
  }

  const handleResetFilters = () => {
    setFilters({
      area: '',
      property_type: '',
      start_date: '',
      end_date: '',
    })
  }

  const tabs = [
    { id: 'overview', name: 'Overview', icon: BarChart3 },
    { id: 'geographic', name: 'Geographic', icon: Globe },
    { id: 'timeseries', name: 'Time Series', icon: TrendingUp },
    { id: 'comparative', name: 'Comparative', icon: BarChart },
    { id: 'areas', name: 'Areas', icon: MapPin },
    { id: 'properties', name: 'Properties', icon: Building2 },
    { id: 'export', name: 'Export & Share', icon: Share2 },
  ]

  const visualizationTypes = [
    { id: 'all', name: 'All Visualizations', icon: Layers },
    { id: 'charts', name: 'Charts Only', icon: BarChart3 },
    { id: 'maps', name: 'Maps Only', icon: Globe },
    { id: 'tables', name: 'Tables Only', icon: Building2 },
  ]

  const summaryStats = summary ? [
    {
      title: 'Total Transactions',
      value: typeof summary.total_transactions === 'number' ? summary.total_transactions.toLocaleString() : '0',
      change: '+12%',
      changeType: 'positive',
      icon: BarChart3,
      color: 'blue'
    },
    {
      title: 'Total Value',
      value: `AED ${typeof summary.total_value === 'number' ? summary.total_value.toLocaleString() : '0'}`,
      change: '+8%',
      changeType: 'positive',
      icon: TrendingUp,
      color: 'green'
    },
    {
      title: 'Average Price',
      value: `AED ${typeof summary.average_price === 'number' ? summary.average_price.toLocaleString() : '0'}`,
      change: '+5%',
      changeType: 'positive',
      icon: Building2,
      color: 'purple'
    },
    {
      title: 'Price per Sqft',
      value: `AED ${typeof summary.average_price_per_sqft === 'number' ? summary.average_price_per_sqft.toFixed(2) : '0'}`,
      change: '+3%',
      changeType: 'positive',
      icon: MapPin,
      color: 'yellow'
    }
  ] : []

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-r from-slate-800 via-slate-700 to-slate-600 rounded-2xl p-6 text-white shadow-xl">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold mb-2 tracking-tight">
              Advanced Analytics
            </h1>
            <p className="text-slate-200 text-base font-normal">
              Comprehensive real estate market insights with interactive visualizations
            </p>
            <div className="flex items-center mt-4 space-x-6">
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                <span className="text-sm font-medium">Live Data</span>
              </div>
              <div className="flex items-center space-x-2">
                <Calendar className="h-4 w-4 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-3">
            <button 
              onClick={() => setShowExportModal(true)}
              className="bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-200 rounded-lg px-4 py-2 flex items-center space-x-2"
            >
              <Download className="h-4 w-4" />
              <span>Export</span>
            </button>
            <button className="bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-200 rounded-lg px-4 py-2 flex items-center space-x-2">
              <Share2 className="h-4 w-4" />
              <span>Share</span>
            </button>
            <button className="bg-white text-slate-700 hover:bg-slate-50 transition-all duration-200 rounded-lg px-4 py-2 flex items-center space-x-2 font-medium">
              <RefreshCw className="h-4 w-4" />
              <span>Refresh</span>
            </button>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="card p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="label">Area</label>
            <input
              type="text"
              placeholder="Enter area..."
              value={filters.area}
              onChange={(e) => handleFilterChange('area', e.target.value)}
              className="input"
            />
          </div>
          <div>
            <label className="label">Property Type</label>
            <select
              value={filters.property_type}
              onChange={(e) => handleFilterChange('property_type', e.target.value)}
              className="input"
            >
              <option value="">All Types</option>
              <option value="Unit">Unit</option>
              <option value="Villa">Villa</option>
              <option value="Land">Land</option>
              <option value="Building">Building</option>
            </select>
          </div>
          <div>
            <label className="label">Start Date</label>
            <input
              type="date"
              value={filters.start_date}
              onChange={(e) => handleFilterChange('start_date', e.target.value)}
              className="input"
            />
          </div>
          <div>
            <label className="label">End Date</label>
            <input
              type="date"
              value={filters.end_date}
              onChange={(e) => handleFilterChange('end_date', e.target.value)}
              className="input"
            />
          </div>
        </div>
        <div className="flex items-center space-x-3 mt-6">
          <button onClick={handleApplyFilters} className="btn btn-primary btn-md">
            <Filter className="h-4 w-4 mr-2" />
            Apply Filters
          </button>
          <button onClick={handleResetFilters} className="btn btn-secondary btn-md">
            Reset Filters
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === tab.id
                  ? 'border-primary-500 text-primary-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <tab.icon className="h-4 w-4 mr-2" />
              {tab.name}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="space-y-6">
          {/* Summary Stats */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {summaryStats.map((stat, index) => (
              <StatCard key={index} {...stat} />
            ))}
          </div>

          {/* Visualization Type Selector */}
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              Visualizations
            </h3>
            <div className="flex items-center space-x-2">
              {visualizationTypes.map(type => (
                <button
                  key={type.id}
                  onClick={() => setSelectedVisualization(type.id)}
                  className={`flex items-center space-x-2 px-3 py-2 rounded-lg border transition-all ${
                    selectedVisualization === type.id
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                      : 'border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-gray-300 dark:hover:border-gray-500'
                  }`}
                >
                  <type.icon className="h-4 w-4" />
                  <span className="text-sm font-medium">{type.name}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Charts Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {(selectedVisualization === 'all' || selectedVisualization === 'charts') && (
              <>
                <div className="card p-6" ref={el => chartRefs.current['transactionVolume'] = el}>
                  <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
                    Transaction Volume Over Time
                  </h3>
                  <Chart
                    data={timeSeriesData}
                    type="line"
                    height={300}
                  />
                </div>
                <div className="card p-6" ref={el => chartRefs.current['areaStats'] = el}>
                  <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
                    Top Areas by Transactions
                  </h3>
                  <Chart
                    data={areaStats}
                    type="bar"
                    height={300}
                  />
                </div>
              </>
            )}
          </div>

          {/* Geographic Map */}
          {(selectedVisualization === 'all' || selectedVisualization === 'maps') && (
            <div ref={mapRef}>
              <GeographicHeatMap
                data={areaStats || []}
                height="500px"
                onAreaClick={(area) => {
                  setFilters(prev => ({ ...prev, area: area.area_en }))
                  setActiveTab('areas')
                }}
                showClusters={true}
                colorScheme="viridis"
              />
            </div>
          )}
        </div>
      )}

      {activeTab === 'geographic' && (
        <div className="space-y-6">
          <GeographicHeatMap
            data={areaStats || []}
            height="600px"
            onAreaClick={(area) => {
              setFilters(prev => ({ ...prev, area: area.area_en }))
            }}
            showClusters={true}
            colorScheme="plasma"
          />
        </div>
      )}

      {activeTab === 'timeseries' && (
        <div className="space-y-6">
          <TimeSeriesChart
            data={timeSeriesData}
            type="line"
            height={500}
            title="Market Trends Over Time"
            subtitle="Transaction volume and value trends"
            showControls={true}
            showTrends={true}
            showForecast={false}
            onExport={(data) => console.log('Export time series:', data)}
            onFullscreen={(data) => console.log('Fullscreen time series:', data)}
          />
        </div>
      )}

      {activeTab === 'comparative' && (
        <div className="space-y-6">
          <ComparativeAnalysis
            data={timeSeriesData}
            comparisonItems={comparisonItems}
            onAddComparison={(item) => {
              setComparisonItems(prev => [...prev, item])
            }}
            onRemoveComparison={(index) => {
              setComparisonItems(prev => prev.filter((_, i) => i !== index))
            }}
            height={500}
            title="Comparative Analysis"
            subtitle="Compare different areas, property types, or time periods"
          />
        </div>
      )}

      {activeTab === 'areas' && (
        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
              Area Performance
            </h3>
            <div className="overflow-x-auto">
              <table className="table">
                <thead className="table-header">
                  <tr className="table-row">
                    <th className="table-head">Area</th>
                    <th className="table-head">Transactions</th>
                    <th className="table-head">Average Price</th>
                    <th className="table-head">Price per Sqft</th>
                    <th className="table-head">Trend</th>
                  </tr>
                </thead>
                <tbody className="table-body">
                  {areaStats?.map((area, index) => (
                    <tr key={index} className="table-row">
                      <td className="table-cell font-medium">{area.area}</td>
                      <td className="table-cell">{area.transaction_count}</td>
                      <td className="table-cell">AED {typeof area.average_price === 'number' ? area.average_price.toLocaleString() : '0'}</td>
                      <td className="table-cell">AED {typeof area.average_price_per_sqft === 'number' ? area.average_price_per_sqft.toFixed(2) : '0'}</td>
                      <td className="table-cell">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          area.price_trend === 'Rising' 
                            ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400'
                            : area.price_trend === 'Falling'
                            ? 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'
                            : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
                        }`}>
                          {area.price_trend}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'properties' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="card p-6">
              <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
                Property Type Distribution
              </h3>
              <Chart
                data={propertyTypeStats}
                type="pie"
                height={300}
              />
            </div>
            <div className="card p-6">
              <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
                Property Type Performance
              </h3>
              <div className="space-y-4">
                {propertyTypeStats?.map((type, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">{type.property_type}</p>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {type.transaction_count} transactions
                      </p>
                    </div>
                    <div className="text-right">
                      <p className="font-medium text-gray-900 dark:text-white">
                        AED {typeof type.average_price === 'number' ? type.average_price.toLocaleString() : '0'}
                      </p>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {typeof type.market_share === 'number' ? type.market_share.toFixed(1) : '0'}% market share
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'export' && (
        <div className="space-y-6">
          <ExportSharing
            data={[
              ...(timeSeriesData || []),
              ...(areaStats || []),
              ...(propertyTypeStats || [])
            ]}
            chartRefs={chartRefs}
            title="Export & Share Analytics"
            onExport={(exportData) => {
              console.log('Export data:', exportData)
              // Handle export logic here
            }}
            onShare={(shareData) => {
              console.log('Share data:', shareData)
              // Handle share logic here
            }}
          />
        </div>
      )}

      {activeTab === 'trends' && (
        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
              Market Trends Analysis
            </h3>
            {marketAnalysis ? (
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="p-4 bg-slate-50 dark:bg-slate-900/20 rounded-lg">
                    <h4 className="font-medium text-slate-900 dark:text-slate-100">Key Metrics</h4>
                    <div className="mt-2 space-y-1 text-sm text-slate-700 dark:text-slate-300">
                      <p>Total Transactions: {marketAnalysis.key_metrics?.total_transactions}</p>
                      <p>Average Price: AED {typeof marketAnalysis.key_metrics?.average_price === 'number' ? marketAnalysis.key_metrics.average_price.toLocaleString() : '0'}</p>
                      <p>Price Volatility: {typeof marketAnalysis.key_metrics?.price_volatility === 'number' ? marketAnalysis.key_metrics.price_volatility.toFixed(2) : '0'}</p>
                    </div>
                  </div>
                  <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-lg">
                    <h4 className="font-medium text-green-900 dark:text-green-100">Trends</h4>
                    <div className="mt-2 space-y-1 text-sm text-green-700 dark:text-green-300">
                      {marketAnalysis.trends?.map((trend, index) => (
                        <p key={index}>• {trend}</p>
                      ))}
                    </div>
                  </div>
                  <div className="p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                    <h4 className="font-medium text-purple-900 dark:text-purple-100">Recommendations</h4>
                    <div className="mt-2 space-y-1 text-sm text-purple-700 dark:text-purple-300">
                      {marketAnalysis.recommendations?.map((rec, index) => (
                        <p key={index}>• {rec}</p>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                Select an area and property type to view market analysis
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

export default Analytics

