import { useQuery } from "@tanstack/react-query"
import { useNavigate } from "@tanstack/react-router"
import { useMemo, useState, useEffect } from "react"
import { api } from "../lib/api"
import { Clock, Calendar, FolderKanban, LogOut, Activity, Download, TrendingUp, TrendingDown, Settings2, X } from "lucide-react"
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"

type WidgetId = 'todayStats' | 'weekStats' | 'activeProjects' | 'chart' | 'activityFeed'

function ActivityFeed() {
  const { data: entries, isLoading } = useQuery({
    queryKey: ["timeEntries", "recent"],
    queryFn: () => api.listTimeEntries({ limit: 10 })
  })

  if (isLoading) return (
    <div className="animate-pulse space-y-3">
      {[...Array(5)].map((_, i) => <div key={i} className="h-12 bg-gray-100 rounded-lg" />)}
    </div>
  )

  return (
    <div className="space-y-4">
      <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wider flex items-center gap-2">
        <Activity size={14} /> Letzte Aktivitäten
      </h3>
      <div className="space-y-3">
        {entries?.length === 0 && <p className="text-sm text-gray-400 italic">Keine aktuellen Einträge</p>}
        {entries?.map((entry: any) => (
          <div key={entry.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
            <div className="flex flex-col">
              <span className="text-sm font-medium text-gray-800">{entry.description}</span>
              <span className="text-xs text-gray-500">{entry.date} • Projekt ID: {entry.projectId}</span>
            </div>
            <span className="text-sm font-semibold text-indigo-600">{entry.duration}h</span>
          </div>
        ))}
      </div>
    </div>
  )
}

export default function Dashboard() {
  const navigate = useNavigate()
  const [isSettingsOpen, setIsSettingsOpen] = useState(false)
  const [visibleWidgets, setVisibleWidgets] = useState<Record<WidgetId, boolean>>({
    todayStats: true,
    weekStats: true,
    activeProjects: true,
    chart: true,
    activityFeed: true,
  })

  useEffect(() => {
    const saved = localStorage.getItem('dashboard_widgets')
    if (saved) {
      try {
        setVisibleWidgets(JSON.parse(saved))
      } catch (e) {
        console.error("Failed to parse dashboard widgets", e)
      }
    }
  }, [])

  const saveWidgets = (newWidgets: Record<WidgetId, boolean>) => {
    setVisibleWidgets(newWidgets)
    localStorage.setItem('dashboard_widgets', JSON.stringify(newWidgets))
  }

  const today = new Date().toISOString().split("T")[0]
  
  const getStartOfWeek = (offsetWeeks = 0) => {
    const d = new Date()
    d.setDate(d.getDate() - (offsetWeeks * 7))
    const day = d.getDay()
    const diff = d.getDate() - day + (day === 0 ? -6 : 1)
    const start = new Date(d.setDate(diff))
    return start.toISOString().split("T")[0]
  }

  const getLast7Days = () => {
    const dates = []
    for (let i = 6; i >= 0; i--) {
      const d = new Date()
      d.setDate(d.getDate() - i)
      dates.push(d.toISOString().split("T")[0])
    }
    return dates
  }

  const weekStart = getStartOfWeek(0)
  const prevWeekStart = getStartOfWeek(1)
  const last7DaysDates = getLast7Days()
  const oldestDate = last7DaysDates[0]

  const { data: user, isLoading: userLoading } = useQuery({
    queryKey: ["me"],
    queryFn: () => api.getMe()
  })

  const { data: todayEntries, isLoading: todayLoading } = useQuery({
    queryKey: ["timeEntries", "today"],
    queryFn: () => api.listTimeEntries({ date: today })
  })

  const { data: weekEntries, isLoading: weekLoading } = useQuery({
    queryKey: ["timeEntries", "week"],
    queryFn: () => api.listTimeEntries({ from: weekStart })
  })

  const { data: chartEntries, isLoading: chartLoading } = useQuery({
    queryKey: ["timeEntries", "chart"],
    queryFn: () => api.listTimeEntries({ from: oldestDate })
  })

  const { data: comparisonEntries } = useQuery({
    queryKey: ["timeEntries", "comparison"],
    queryFn: () => api.listTimeEntries({ from: prevWeekStart })
  })

  const handleLogout = () => {
    api.logout()
    navigate({ to: "/login" })
  }

  const handleExportReport = () => {
    const from = weekStart
    const to = today
    window.open(`/api/reports/pdf?from=${from}&to=${to}`, '_blank')
  }

  const stats = useMemo(() => {
    const currentWeekHours = weekEntries?.reduce((acc, curr) => acc + (parseFloat(curr.duration) || 0), 0) || 0
    const prevWeekHours = comparisonEntries?.reduce((acc, curr) => {
      const entryDate = new Date(curr.date)
      const start = new Date(prevWeekStart)
      const end = new Date(weekStart)
      if (entryDate >= start && entryDate < end) {
        return acc + (parseFloat(curr.duration) || 0)
      }
      return acc
    }, 0) || 0

    const diff = currentWeekHours - prevWeekHours
    const percent = prevWeekHours === 0 ? 0 : (diff / prevWeekHours) * 100

    return { currentWeekHours, prevWeekHours, diff, percent }
  }, [weekEntries, comparisonEntries, prevWeekStart, weekStart])

  const chartData = useMemo(() => {
    const dataMap: Record<string, number> = {}
    last7DaysDates.forEach(d => dataMap[d] = 0)
    chartEntries?.forEach(entry => {
      if (dataMap[entry.date] !== undefined) {
        dataMap[entry.date] += parseFloat(entry.duration) || 0
      }
    })
    return Object.entries(dataMap).map(([date, hours]) => ({
      date: date.split("-").slice(1).join("."),
      hours
    }))
  }, [chartEntries, last7DaysDates])

  if (userLoading) return <div className="p-8 text-center">Lade Dashboard...</div>

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Willkommen, {user?.name}</h1>
          <p className="text-gray-500">Hier ist deine Übersicht für heute.</p>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={() => setIsSettingsOpen(true)}
            className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <Settings2 size={16} /> Anpassen
          </button>
          <button 
            onClick={handleExportReport}
            className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors"
          >
            <Download size={16} /> Export
          </button>
          <button 
            onClick={handleLogout}
            className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
          >
            <LogOut size={16} /> Logout
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {visibleWidgets.todayStats && (
          <div className="p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-indigo-100 text-indigo-600 rounded-lg"><Clock size={20} /></div>
              <h3 className="font-semibold text-gray-700">Heute</h3>
            </div>
            <div className="text-3xl font-bold text-gray-900">
              {todayEntries?.reduce((acc, curr) => acc + (parseFloat(curr.duration) || 0), 0).toFixed(2) || "0.00"}h
            </div>
            <p className="text-xs text-gray-400 mt-1">Gebuchte Zeit heute</p>
          </div>
        )}

        {visibleWidgets.weekStats && (
          <div className="p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-green-100 text-green-600 rounded-lg"><Calendar size={20} /></div>
              <h3 className="font-semibold text-gray-700">Diese Woche</h3>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-gray-900">{stats.currentWeekHours.toFixed(2)}h</span>
              <div className={`flex items-center text-xs font-medium ${stats.diff >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {stats.diff >= 0 ? <TrendingUp size={12} className="mr-1" /> : <TrendingDown size={12} className="mr-1" />}
                {Math.abs(stats.percent).toFixed(1)}%
              </div>
            </div>
            <p className="text-xs text-gray-400 mt-1">Im Vergleich zur Vorwoche</p>
          </div>
        )}

        {visibleWidgets.activeProjects && (
          <div className="p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-amber-100 text-amber-600 rounded-lg"><FolderKanban size={20} /></div>
              <h3 className="font-semibold text-gray-700">Aktive Projekte</h3>
            </div>
            <div className="text-3xl font-bold text-gray-900">
              {new Set(weekEntries?.map(e => e.projectId)).size || 0}
            </div>
            <p className="text-xs text-gray-400 mt-1">Projekte in dieser Woche</p>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {visibleWidgets.chart && (
          <div className="lg:col-span-2 p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
            <h3 className="text-lg font-semibold text-gray-800 mb-6">Zeitverlauf (7 Tage)</h3>
            <div className="h-64 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f3f4f6" />
                  <XAxis dataKey="date" axisLine={false} tickLine={false} tick={{fontSize: 12, fill: '#9ca3af'}} />
                  <YAxis axisLine={false} tickLine={false} tick={{fontSize: 12, fill: '#9ca3af'}} />
                  <Tooltip 
                    cursor={{fill: '#f9fafb'}} 
                    contentStyle={{borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'}} 
                  />
                  <Bar dataKey="hours" fill="#4f46e5" radius={[4, 4, 0, 0]} barSize={30} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}

        {visibleWidgets.activityFeed && (
          <div className="p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
            <ActivityFeed />
          </div>
        )}
      </div>

      {isSettingsOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6 relative">
            <button 
              onClick={() => setIsSettingsOpen(false)}
              className="absolute right-4 top-4 p-1 text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X size={20} />
            </button>
            <h2 className="text-xl font-bold text-gray-900 mb-6">Dashboard anpassen</h2>
            <div className="space-y-4">
              {(Object.keys(visibleWidgets) as WidgetId[]).map((id) => (
                <label key={id} className="flex items-center justify-between p-3 rounded-lg border border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors">
                  <span className="text-sm font-medium text-gray-700">
                    {id === 'todayStats' && 'Heutige Statistik'}
                    {id === 'weekStats' && 'Wochenstatistik'}
                    {id === 'activeProjects' && 'Aktive Projekte'}
                    {id === 'chart' && 'Zeit-Chart'}
                    {id === 'activityFeed' && 'Aktivitäts-Feed'}
                  </span>
                  <input 
                    type="checkbox" 
                    className="w-4 h-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500"
                    checked={visibleWidgets[id]}
                    onChange={(e) => {
                      saveWidgets({ ...visibleWidgets, [id]: e.target.checked })
                    }}
                  />
                </label>
              ))}
            </div>
            <button 
              onClick={() => setIsSettingsOpen(false)}
              className="w-full mt-8 py-2 bg-indigo-600 text-white rounded-lg font-medium hover:bg-indigo-700 transition-colors"
            >
              Fertig
            </button>
          </div>
        </div>
      )}
    </div>
  )
}