'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { 
  BarChart2, History, TrendingUp, Download, 
  Calendar, Filter, Activity 
} from 'lucide-react'
import { useLiveQuery } from 'dexie-react-hooks'
import { format, subDays, startOfDay, isSameDay, subWeeks, subMonths } from 'date-fns'

import { db } from '@/lib/sync'
import { Card, LoadingState, Button, showToast } from '@/components/ui'
import { Header, PageContainer } from '@/components/layout/header'
import { SymptomQuickLog } from '@/components/symptoms/SymptomQuickLog'
import { SymptomCard } from '@/components/symptoms/SymptomCard'
import { SymptomTrendChart } from '@/components/symptoms/SymptomTrendChart'
import { SymptomReportGenerator } from '@/components/symptoms/SymptomReportGenerator'
import { useApp } from '../provider'

const TIME_RANGES = [
  { value: '7', label: '7 Days' },
  { value: '14', label: '14 Days' },
  { value: '30', label: '30 Days' },
]

const SYMPTOM_TYPES = [
  { type: 'FATIGUE', emoji: '😴', label: 'Fatigue', color: '#8b5cf6' },
  { type: 'NAUSEA', emoji: '🤢', label: 'Nausea', color: '#f59e0b' },
  { type: 'PAIN', emoji: '😣', label: 'Pain', color: '#ef4444' },
  { type: 'APPETITE', emoji: '🍽️', label: 'Appetite', color: '#10b981' },
  { type: 'SLEEP', emoji: '😴', label: 'Sleep', color: '#3b82f6' },
  { type: 'MOOD', emoji: '😔', label: 'Mood', color: '#ec4899' },
]

export default function EnhancedSymptomsPage() {
  const router = useRouter()
  const { currentWorkspace, refreshData } = useApp()
  const [recentSymptoms, setRecentSymptoms] = useState<any[]>([])
  const [timeRange, setTimeRange] = useState('7')
  const [selectedType, setSelectedType] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [showReport, setShowReport] = useState(false)

  // Fetch symptoms from IndexedDB
  const localSymptoms = useLiveQuery(
    () =>
      db.symptoms
        .where('workspaceId')
        .equals(currentWorkspace.id)
        .and((s) => !s.deletedAt)
        .reverse()
        .toArray(),
    [currentWorkspace.id]
  )

  // Fetch from server
  const fetchSymptoms = useCallback(async () => {
    try {
      const response = await fetch(
        `/api/workspaces/${currentWorkspace.id}/symptoms?limit=100`
      )
      if (response.ok) {
        const data = await response.json()
        setRecentSymptoms(data.symptoms)
      }
    } catch (err) {
      console.error('Failed to fetch symptoms:', err)
    } finally {
      setLoading(false)
    }
  }, [currentWorkspace.id])

  useEffect(() => {
    fetchSymptoms()
  }, [fetchSymptoms])

  const handleLogged = () => {
    fetchSymptoms()
    refreshData()
  }

  // Combine local and server data
  const symptoms = recentSymptoms.length > 0 ? recentSymptoms : localSymptoms || []

  // Filter by time range
  const daysBack = parseInt(timeRange)
  const cutoffDate = subDays(new Date(), daysBack)
  const filteredSymptoms = symptoms.filter(s => 
    new Date(s.recordedAt) >= cutoffDate &&
    (!selectedType || s.type === selectedType)
  )

  // Calculate stats
  const stats = useMemo(() => {
    const byType: Record<string, { count: number; avgSeverity: number }> = {}
    
    filteredSymptoms.forEach(s => {
      if (!byType[s.type]) {
        byType[s.type] = { count: 0, avgSeverity: 0 }
      }
      byType[s.type].count++
      byType[s.type].avgSeverity += s.severity
    })
    
    // Calculate averages
    Object.keys(byType).forEach(type => {
      byType[type].avgSeverity = Math.round((byType[type].avgSeverity / byType[type].count) * 10) / 10
    })
    
    return byType
  }, [filteredSymptoms])

  // Find patterns (days with multiple symptoms)
  const patterns = useMemo(() => {
    const byDate: Record<string, any[]> = {}
    filteredSymptoms.forEach(s => {
      const date = format(new Date(s.recordedAt), 'yyyy-MM-dd')
      if (!byDate[date]) byDate[date] = []
      byDate[date].push(s)
    })
    
    return Object.entries(byDate)
      .filter(([_, items]) => items.length >= 2)
      .sort((a, b) => b[0].localeCompare(a[0]))
      .slice(0, 5)
  }, [filteredSymptoms])

  if (loading && !localSymptoms) {
    return (
      <>
        <Header title="Symptom Insights" />
        <PageContainer>
          <LoadingState message="Loading symptoms..." />
        </PageContainer>
      </>
    )
  }

  return (
    <>
      <Header
        title="Symptom Insights"
        rightAction={{
          icon: <History className="w-6 h-6 text-secondary-700" />,
          label: 'History',
          onClick: () => router.push('/symptoms/history'),
        }}
      />
      <PageContainer className="pt-4 space-y-6">
        {/* Quick Log */}
        <section>
          <h2 className="text-lg font-semibold text-secondary-900 mb-3">Log a Symptom</h2>
          <Card>
            <SymptomQuickLog
              workspaceId={currentWorkspace.id}
              onLogged={handleLogged}
              medications={medications}
            />
          </Card>
        </section>

        {/* Time Range & Filters */}
        <section>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold text-secondary-900 flex items-center">
              <TrendingUp className="w-5 h-5 mr-2" />
              Trends & Insights
            </h2>
            <Button 
              variant="ghost" 
              size="sm"
              onClick={() => setShowReport(true)}
            >
              <Download className="w-4 h-4 mr-1" />
              Report
            </Button>
          </div>

          {/* Time Range Selector */}
          <div className="flex gap-2 mb-4">
            {TIME_RANGES.map(range => (
              <button
                key={range.value}
                onClick={() => setTimeRange(range.value)}
                className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
                  timeRange === range.value
                    ? 'bg-primary-500 text-white'
                    : 'bg-secondary-100 text-secondary-600 hover:bg-secondary-200'
                }`}
              >
                {range.label}
              </button>
            ))}
          </div>

          {/* Symptom Type Filter */}
          <div className="flex flex-wrap gap-2 mb-4">
            <button
              onClick={() => setSelectedType(null)}
              className={`px-3 py-1.5 rounded-full text-sm transition-all ${
                selectedType === null
                  ? 'bg-secondary-800 text-white'
                  : 'bg-secondary-100 text-secondary-600'
              }`}
            >
              All
            </button>
            {SYMPTOM_TYPES.map(type => (
              <button
                key={type.type}
                onClick={() => setSelectedType(type.type)}
                className={`px-3 py-1.5 rounded-full text-sm transition-all flex items-center gap-1 ${
                  selectedType === type.type
                    ? 'text-white'
                    : 'bg-secondary-100 text-secondary-600'
                }`}
                style={{
                  backgroundColor: selectedType === type.type ? type.color : undefined
                }}
              >
                <span>{type.emoji}</span>
                <span>{type.label}</span>
              </button>
            ))}
          </div>
        </section>

        {/* Trend Chart */}
        {filteredSymptoms.length > 0 && (
          <Card>
            <SymptomTrendChart
              symptoms={filteredSymptoms}
              days={parseInt(timeRange)}
              selectedType={selectedType}
            />
          </Card>
        )}

        {/* Stats Summary */}
        {Object.keys(stats).length > 0 && (
          <Card>
            <h3 className="font-semibold text-secondary-900 mb-3 flex items-center">
              <Activity className="w-5 h-5 mr-2 text-primary-500" />
              Summary ({timeRange} Days)
            </h3>
            <div className="space-y-3">
              {Object.entries(stats).map(([type, data]) => {
                const typeInfo = SYMPTOM_TYPES.find(t => t.type === type)
                return (
                  <div key={type} className="flex items-center justify-between p-3 bg-secondary-50 rounded-lg">
                    <div className="flex items-center gap-3">
                      <span className="text-xl">{typeInfo?.emoji}</span>
                      <div>
                        <p className="font-medium text-secondary-900">{typeInfo?.label}</p>
                        <p className="text-xs text-secondary-500">{data.count} logged</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-semibold text-secondary-900">{data.avgSeverity}/5</p>
                      <p className="text-xs text-secondary-500">avg severity</p>
                    </div>
                  </div>
                )
              })}
            </div>
          </Card>
        )}

        {/* Patterns */}
        {patterns.length > 0 && (
          <Card>
            <h3 className="font-semibold text-secondary-900 mb-3 flex items-center">
              <Calendar className="w-5 h-5 mr-2 text-primary-500" />
              Patterns Noticed
            </h3>
            <p className="text-sm text-secondary-500 mb-3">
              Days with multiple symptoms logged
            </p>
            <div className="space-y-2">
              {patterns.map(([date, items]) => (
                <div key={date} className="p-3 bg-amber-50 border border-amber-100 rounded-lg">
                  <p className="font-medium text-secondary-900">
                    {format(new Date(date), 'EEEE, MMM d')}
                  </p>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {items.map((item, i) => (
                      <span 
                        key={i}
                        className="text-xs px-2 py-0.5 bg-white rounded-full text-secondary-600"
                      >
                        {SYMPTOM_TYPES.find(t => t.type === item.type)?.label} ({item.severity}/5)
                      </span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        )}

        {/* Recent Symptoms */}
        <section>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold text-secondary-900">Recent</h2>
            {symptoms.length > 5 && (
              <button
                onClick={() => router.push('/symptoms/history')}
                className="text-sm text-primary-600 font-medium"
              >
                View all
              </button>
            )}
          </div>

          {symptoms.length === 0 ? (
            <Card variant="outline" className="text-center py-8">
              <BarChart2 className="w-10 h-10 text-secondary-300 mx-auto mb-3" />
              <p className="text-secondary-500">No symptoms logged yet</p>
              <p className="text-sm text-secondary-400 mt-1">
                Use the form above to track how you're feeling
              </p>
            </Card>
          ) : (
            <div className="space-y-3">
              {symptoms.slice(0, 5).map((symptom: any) => (
                <SymptomCard key={symptom.id} symptom={symptom} />
              ))}
            </div>
          )}
        </section>
      </PageContainer>

      {/* Report Modal */}
      {showReport && (
        <SymptomReportGenerator
          symptoms={filteredSymptoms}
          workspaceId={currentWorkspace.id}
          timeRange={parseInt(timeRange)}
          onClose={() => setShowReport(false)}
        />
      )}
    </>
  )
}
