'use client'

import { useMemo } from 'react'
import { format, subDays, startOfDay, isSameDay } from 'date-fns'

interface Symptom {
  id: string
  type: string
  severity: number
  recordedAt: string
  durationMinutes?: number
  triggers?: string
  medicationTaken?: string
}

interface SymptomTrendChartProps {
  symptoms: Symptom[]
  days?: number
  selectedType?: string | null
}

const SYMPTOM_COLORS: Record<string, string> = {
  FATIGUE: '#8b5cf6',
  NAUSEA: '#f59e0b',
  PAIN: '#ef4444',
  APPETITE: '#10b981',
  SLEEP: '#3b82f6',
  MOOD: '#ec4899',
  CUSTOM: '#6b7280',
}

const SYMPTOM_EMOJIS: Record<string, string> = {
  FATIGUE: '😴',
  NAUSEA: '🤢',
  PAIN: '😣',
  APPETITE: '🍽️',
  SLEEP: '😴',
  MOOD: '😔',
  CUSTOM: '📝',
}

export function SymptomTrendChart({ symptoms, days = 7, selectedType }: SymptomTrendChartProps) {
  // Generate date range
  const today = startOfDay(new Date())
  const dates = useMemo(() => 
    Array.from({ length: days }, (_, i) => subDays(today, days - 1 - i)),
    [days, today]
  )

  // Group symptoms by type and date
  const dataByTypeAndDate = useMemo(() => {
    const result: Record<string, Record<string, { avgSeverity: number; count: number }>> = {}
    
    symptoms.forEach(s => {
      if (selectedType && s.type !== selectedType) return
      
      const dateKey = format(new Date(s.recordedAt), 'yyyy-MM-dd')
      if (!result[s.type]) result[s.type] = {}
      if (!result[s.type][dateKey]) {
        result[s.type][dateKey] = { avgSeverity: 0, count: 0 }
      }
      result[s.type][dateKey].avgSeverity += s.severity
      result[s.type][dateKey].count++
    })
    
    // Calculate averages
    Object.keys(result).forEach(type => {
      Object.keys(result[type]).forEach(date => {
        const data = result[type][date]
        data.avgSeverity = data.avgSeverity / data.count
      })
    })
    
    return result
  }, [symptoms, selectedType])

  // Get unique types
  const types = selectedType ? [selectedType] : Object.keys(dataByTypeAndDate)

  if (symptoms.length === 0) {
    return (
      <div className="text-center py-8 text-secondary-500">
        No symptom data to display
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Chart Area */}
      <div className="h-48 relative">
        {/* Grid lines */}
        <div className="absolute inset-0 flex flex-col justify-between">
          {[5, 4, 3, 2, 1].map(level => (
            <div key={level} className="flex items-center">
              <span className="w-4 text-xs text-secondary-400">{level}</span>
              <div className="flex-1 border-t border-secondary-100" />
            </div>
          ))}
        </div>
        
        {/* Bars */}
        <div className="absolute inset-0 pl-6 flex items-end gap-1">
          {dates.map((date, i) => {
            const dateKey = format(date, 'yyyy-MM-dd')
            const dayData: Record<string, number> = {}
            
            types.forEach(type => {
              if (dataByTypeAndDate[type]?.[dateKey]) {
                dayData[type] = dataByTypeAndDate[type][dateKey].avgSeverity
              }
            })
            
            const hasData = Object.keys(dayData).length > 0
            
            return (
              <div key={i} className="flex-1 flex flex-col items-center">
                <div className="w-full flex items-end justify-center gap-0.5 h-40">
                  {hasData ? (
                    types.map(type => {
                      const severity = dayData[type]
                      if (!severity) return null
                      const height = (severity / 5) * 100
                      return (
                        <div
                          key={type}
                          className="w-full rounded-t transition-all hover:opacity-80"
                          style={{
                            height: `${height}%`,
                            backgroundColor: SYMPTOM_COLORS[type] || '#6b7280',
                            minHeight: '4px',
                          }}
                          title={`${type}: ${severity.toFixed(1)}/5`}
                        />
                      )
                    })
                  ) : (
                    <div className="w-full h-1 bg-secondary-100 rounded" />
                  )}
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* Date labels */}
      <div className="flex pl-6">
        {dates.map((date, i) => (
          <div key={i} className="flex-1 text-center">
            <span className="text-xs text-secondary-500">
              {format(date, days > 14 ? 'd' : 'EEE')}
            </span>
          </div>
        ))}
      </div>

      {/* Legend */}
      {!selectedType && types.length > 0 && (
        <div className="flex flex-wrap justify-center gap-3 pt-2 border-t border-border">
          {types.map(type => (
            <div key={type} className="flex items-center gap-1">
              <div 
                className="w-3 h-3 rounded"
                style={{ backgroundColor: SYMPTOM_COLORS[type] || '#6b7280' }}
              />
              <span className="text-xs text-secondary-600">
                {SYMPTOM_EMOJIS[type]} {type.charAt(0) + type.slice(1).toLowerCase()}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
