import React, { useState, useMemo } from 'react'
import { Line, Bar, Scatter } from 'react-chartjs-2'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js'
import { 
  BarChart3, 
  LineChart, 
  Activity,
  TrendingUp, 
  TrendingDown,
  Plus,
  X,
  Download,
  Settings,
  Filter,
  ArrowUpRight,
  ArrowDownRight,
  Minus
} from 'lucide-react'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

const ComparativeAnalysis = ({ 
  data = [],
  comparisonItems = [],
  onAddComparison,
  onRemoveComparison,
  height = 400,
  title = 'Comparative Analysis',
  subtitle = 'Compare different areas, property types, or time periods'
}) => {
  const [chartType, setChartType] = useState('line')
  const [metric, setMetric] = useState('transactions')
  const [showSettings, setShowSettings] = useState(false)
  const [normalizeData, setNormalizeData] = useState(false)
  const [showTrends, setShowTrends] = useState(true)

  const availableMetrics = [
    { key: 'transactions', label: 'Transaction Count', color: 'rgb(59, 130, 246)' },
    { key: 'value', label: 'Total Value (AED)', color: 'rgb(16, 185, 129)' },
    { key: 'average_price', label: 'Average Price (AED)', color: 'rgb(245, 158, 11)' },
    { key: 'price_per_sqft', label: 'Price per Sqft (AED)', color: 'rgb(239, 68, 68)' }
  ]

  const chartTypes = [
    { key: 'line', label: 'Line Chart', icon: LineChart },
    { key: 'bar', label: 'Bar Chart', icon: BarChart3 },
    { key: 'scatter', label: 'Scatter Plot', icon: Activity }
  ]

  // Process data for comparison
  const processedData = useMemo(() => {
    if (!data || data.length === 0) return { labels: [], datasets: [] }

    // Group data by comparison items
    const groupedData = {}
    const allDates = new Set()

    data.forEach(item => {
      const key = `${item.area_en || 'Unknown'}_${item.property_type || 'All'}`
      if (!groupedData[key]) {
        groupedData[key] = {
          area: item.area_en || 'Unknown',
          propertyType: item.property_type || 'All',
          data: []
        }
      }
      groupedData[key].data.push(item)
      allDates.add(item.date)
    })

    // Sort dates
    const sortedDates = Array.from(allDates).sort((a, b) => new Date(a) - new Date(b))
    const labels = sortedDates.map(date => 
      new Date(date).toLocaleDateString('en-US', { 
        month: 'short', 
        day: 'numeric' 
      })
    )

    // Create datasets for each comparison item
    const datasets = Object.values(groupedData).map((group, index) => {
      const color = availableMetrics.find(m => m.key === metric)?.color || 
        `hsl(${(index * 137.5) % 360}, 70%, 50%)`
      
      const values = sortedDates.map(date => {
        const item = group.data.find(d => d.date === date)
        if (!item) return null

        let value = item[metric] || 0
        
        // Normalize data if requested
        if (normalizeData && metric !== 'transactions') {
          const maxValue = Math.max(...group.data.map(d => d[metric] || 0))
          value = maxValue > 0 ? (value / maxValue) * 100 : 0
        }

        return value
      })

      // Calculate trend
      const validValues = values.filter(v => v !== null)
      const trend = validValues.length >= 2 ? 
        ((validValues[validValues.length - 1] - validValues[0]) / validValues[0]) * 100 : 0

      return {
        label: `${group.area} (${group.propertyType})`,
        data: values,
        borderColor: color,
        backgroundColor: `${color}20`,
        tension: 0.4,
        fill: false,
        pointRadius: 4,
        pointHoverRadius: 6,
        pointBackgroundColor: color,
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        trend: trend,
        totalValue: group.data.reduce((sum, item) => sum + (item[metric] || 0), 0),
        averageValue: validValues.length > 0 ? validValues.reduce((sum, val) => sum + val, 0) / validValues.length : 0
      }
    })

    return { labels, datasets }
  }, [data, metric, normalizeData])

  const renderChart = () => {
    const options = {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: 'index',
        intersect: false,
      },
      plugins: {
        legend: {
          display: true,
          position: 'top',
          labels: {
            usePointStyle: true,
            padding: 20,
            font: {
              size: 12,
              weight: '500'
            }
          }
        },
        tooltip: {
          mode: 'index',
          intersect: false,
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          titleColor: 'white',
          bodyColor: 'white',
          borderColor: 'rgba(255, 255, 255, 0.1)',
          borderWidth: 1,
          cornerRadius: 8,
          displayColors: true,
          callbacks: {
            label: function(context) {
              const value = context.parsed.y
              if (normalizeData && metric !== 'transactions') {
                return `${context.dataset.label}: ${value.toFixed(1)}%`
              }
              if (metric === 'value' || metric === 'average_price' || metric === 'price_per_sqft') {
                return `${context.dataset.label}: AED ${value.toLocaleString()}`
              }
              return `${context.dataset.label}: ${value.toLocaleString()}`
            }
          }
        }
      },
      scales: {
        x: {
          display: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)',
            drawBorder: false
          },
          ticks: {
            font: {
              size: 11
            },
            color: '#6B7280',
            maxRotation: 45,
            minRotation: 0
          }
        },
        y: {
          display: true,
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)',
            drawBorder: false
          },
          ticks: {
            callback: function(value) {
              if (normalizeData && metric !== 'transactions') {
                return `${value.toFixed(0)}%`
              }
              if (metric === 'value' || metric === 'average_price' || metric === 'price_per_sqft') {
                return `AED ${value.toLocaleString()}`
              }
              return value.toLocaleString()
            },
            font: {
              size: 11
            },
            color: '#6B7280'
          }
        }
      },
      elements: {
        line: {
          tension: 0.4,
          borderWidth: 3
        },
        point: {
          radius: 4,
          hoverRadius: 6,
          borderWidth: 2
        }
      }
    }

    switch (chartType) {
      case 'bar':
        return <Bar data={processedData} options={options} />
      case 'scatter':
        return <Scatter data={processedData} options={options} />
      default:
        return <Line data={processedData} options={options} />
    }
  }

  const handleExport = () => {
    // Export functionality would be implemented here
    console.log('Exporting comparison data:', processedData)
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700">
      {/* Header */}
      <div className="p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-1">
              {title}
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {subtitle}
            </p>
          </div>
          
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setShowSettings(!showSettings)}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              title="Settings"
            >
              <Settings className="h-4 w-4" />
            </button>
            <button
              onClick={handleExport}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              title="Export"
            >
              <Download className="h-4 w-4" />
            </button>
          </div>
        </div>

        {/* Controls */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            {/* Chart Type */}
            <div className="flex items-center space-x-2">
              {chartTypes.map(type => (
                <button
                  key={type.key}
                  onClick={() => setChartType(type.key)}
                  className={`p-2 rounded-lg transition-colors ${
                    chartType === type.key 
                      ? 'bg-blue-100 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' 
                      : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                  }`}
                  title={type.label}
                >
                  <type.icon className="h-4 w-4" />
                </button>
              ))}
            </div>

            {/* Metric Selection */}
            <select
              value={metric}
              onChange={(e) => setMetric(e.target.value)}
              className="text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              {availableMetrics.map(metricOption => (
                <option key={metricOption.key} value={metricOption.key}>
                  {metricOption.label}
                </option>
              ))}
            </select>

            {/* Add Comparison Button */}
            <button
              onClick={onAddComparison}
              className="flex items-center space-x-1 px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors text-sm"
            >
              <Plus className="h-4 w-4" />
              <span>Add Comparison</span>
            </button>
          </div>

          {/* Trend Indicators */}
          {showTrends && processedData.datasets.length > 0 && (
            <div className="flex items-center space-x-4">
              {processedData.datasets.slice(0, 3).map((dataset, index) => (
                <div key={index} className="flex items-center space-x-1">
                  {dataset.trend >= 0 ? (
                    <TrendingUp className="h-4 w-4 text-green-500" />
                  ) : (
                    <TrendingDown className="h-4 w-4 text-red-500" />
                  )}
                  <span className={`text-sm font-medium ${
                    dataset.trend >= 0 ? 'text-green-600' : 'text-red-600'
                  }`}>
                    {Math.abs(dataset.trend).toFixed(1)}%
                  </span>
                  <span className="text-xs text-gray-500 truncate max-w-20">
                    {dataset.label.split(' ')[0]}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Settings Panel */}
        {showSettings && (
          <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-3">Chart Settings</h4>
            <div className="grid grid-cols-2 gap-4">
              <label className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={normalizeData}
                  onChange={(e) => setNormalizeData(e.target.checked)}
                  className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Normalize Data</span>
              </label>
              <label className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={showTrends}
                  onChange={(e) => setShowTrends(e.target.checked)}
                  className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Show Trends</span>
              </label>
            </div>
          </div>
        )}
      </div>

      {/* Chart */}
      <div className="p-6">
        <div style={{ height: `${height}px` }}>
          {processedData.labels.length > 0 ? (
            renderChart()
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <BarChart3 className="h-16 w-16 text-gray-400 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  No Comparison Data
                </h3>
                <p className="text-gray-500 dark:text-gray-400">
                  Add items to compare or adjust your filters
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Summary Stats */}
      {processedData.datasets.length > 0 && (
        <div className="p-6 border-t border-gray-200 dark:border-gray-700">
          <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-3">Summary Statistics</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {processedData.datasets.map((dataset, index) => (
              <div key={index} className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div className="flex items-center justify-between mb-2">
                  <h5 className="text-sm font-medium text-gray-900 dark:text-white truncate">
                    {dataset.label}
                  </h5>
                  <div className="flex items-center space-x-1">
                    {dataset.trend >= 0 ? (
                      <ArrowUpRight className="h-3 w-3 text-green-500" />
                    ) : (
                      <ArrowDownRight className="h-3 w-3 text-red-500" />
                    )}
                    <span className={`text-xs font-medium ${
                      dataset.trend >= 0 ? 'text-green-600' : 'text-red-600'
                    }`}>
                      {Math.abs(dataset.trend).toFixed(1)}%
                    </span>
                  </div>
                </div>
                <div className="space-y-1 text-xs text-gray-600 dark:text-gray-400">
                  <div className="flex justify-between">
                    <span>Total:</span>
                    <span className="font-medium">
                      {normalizeData && metric !== 'transactions' 
                        ? `${dataset.totalValue.toFixed(1)}%`
                        : metric === 'value' || metric === 'average_price' || metric === 'price_per_sqft'
                        ? `AED ${dataset.totalValue.toLocaleString()}`
                        : dataset.totalValue.toLocaleString()
                      }
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span>Average:</span>
                    <span className="font-medium">
                      {normalizeData && metric !== 'transactions' 
                        ? `${dataset.averageValue.toFixed(1)}%`
                        : metric === 'value' || metric === 'average_price' || metric === 'price_per_sqft'
                        ? `AED ${dataset.averageValue.toLocaleString()}`
                        : dataset.averageValue.toLocaleString()
                      }
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

export default ComparativeAnalysis
