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, ChevronRight } from "lucide-react"
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"

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

function RecentProjects() {
  const { data: projects, isLoading } = useQuery({
    queryKey: ["projects", "recent"],
    queryFn: () => api.listProjects({ limit: 5 })
  })

  if (isLoading) return (
    <div className="animate-pulse space-y-3">
      {[...Array(3)].map((_, i) => <div key={i} className="h-16 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">
        <FolderKanban size={14} /> Aktive Projekte
      </h3>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        {projects?.length === 0 && <p className="text-sm text-gray-400 italic">Keine Projekte gefunden</p>}
        {projects?.map((project: any) => (
          <div key={project.id} className="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 hover:border-indigo-300 transition-colors cursor-pointer group">
            <div className="flex flex-col">
              <span className="text-sm font-medium text-gray-800 group-hover:text-indigo-600 transition-colors">{project.name}</span>
              <span className="text-xs text-gray-500">{project.client || 'Intern'}</span>
            </div>
            <ChevronRight size={16} className="text-gray-300 group-hover:text-indigo-400" />
          </div>
        ))}
      </div>
    </div>
  )
}

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 todayTotal = useMemo(() => 
    todayEntries?.reduce((acc: number, e: any) => acc + parseFloat(e.duration || 0), 0) || 0, 
  [todayEntries])

  const weekTotal = useMemo(() => 
    weekEntries?.reduce((acc: number, e: any) => acc + parseFloat(e.duration || 0), 0) || 0, 
  [weekEntries])

  const prevWeekTotal = useMemo(() => 
    comparisonEntries?.reduce((acc: number, e: any) => acc + parseFloat(e.duration || 0), 0) || 0, 
  [comparisonEntries])

  const weekDiff = weekTotal - prevWeekTotal

  const chartData = useMemo(() => {
    if (!chartEntries) return []
    return last7DaysDates.map(date => {
      const dayTotal = chartEntries
        .filter((e: any) => e.date === date)
        .reduce((acc: number, e: any) => acc + parseFloat(e.duration || 0), 0)
      return { date: date.slice(5), hours: dayTotal }
    })
  }, [chartEntries])

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

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-8">
      <header className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Willkommen zurück, {user?.name}</h1>
          <p className="text-gray-500">Hier ist die Übersicht deiner Zeitbuchungen.</p>
        </div>
        <button 
          onClick={() => setIsSettingsOpen(true)}
          className="p-2 text-gray-400 hover:text-indigo-600 transition-colors"
        >
          <Settings2 size={20} />
        </button>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {visibleWidgets.todayStats && (
          <div className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg">
                <Clock size={20} />
              </div>
              <span className="text-xs font-medium text-gray-400 uppercase">Heute</span>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-gray-900">{todayTotal.toFixed(2)}h</span>
              <span className="text-sm text-gray-500">gebucht</span>
            </div>
          </div>
        )}

        {visibleWidgets.weekStats && (
          <div className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <div className="p-2 bg-emerald-50 text-emerald-600 rounded-lg">
                <Calendar size={20} />
              </div>
              <span className="text-xs font-medium text-gray-400 uppercase">Diese Woche</span>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-gray-900">{weekTotal.toFixed(2)}h</span>
              {weekDiff !== 0 && (
                <div className={`flex items-center text-xs font-medium ${weekDiff > 0 ? 'text-emerald-600' : 'text-rose-600'}`}>
                  {weekDiff > 0 ? <TrendingUp size={12} className="mr-1" /> : <TrendingDown size={12} className="mr-1" />}
                  {Math.abs(weekDiff).toFixed(2)}h
                </div>
              )}
            </div>
          </div>
        )}

        {visibleWidgets.activeProjects && (
          <div className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <div className="p-2 bg-amber-50 text-amber-600 rounded-lg">
                <FolderKanban size={20} />
              </div>
              <span className="text-xs font-medium text-gray-400 uppercase">Projekte</span>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-gray-900">
                {useQuery({ queryKey: ["projects"], queryFn: () => api.listProjects() }).data?.length || 0}
              </span>
              <span className="text-sm text-gray-500">aktiv</span>
            </div>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          {visibleWidgets.chart && (
            <div className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
              <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wider 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="#6366f1" radius={[4, 4, 0, 0]} barSize={32} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
          )}

          <RecentProjects />
        </div>

        <div className="space-y-8">
          {visibleWidgets.activityFeed && <ActivityFeed />}
          
          <div className="bg-indigo-600 rounded-2xl p-6 text-white shadow-lg shadow-indigo-200">
            <h3 className="font-bold text-lg mb-2">Exportieren</h3>
            <p className="text-indigo-100 text-sm mb-4">Lade deine Zeitbuchungen als CSV für die Abrechnung herunter.</p>
            <button 
              onClick={() => window.open('/api/time-entries/export', '_blank')}
              className="w-full py-2 bg-white text-indigo-600 rounded-lg font-semibold text-sm flex items-center justify-center gap-2 hover:bg-indigo-50 transition-colors"
            >
              <Download size={16} /> CSV Export
            </button>
          </div>
        </div>
      </div>

      {isSettingsOpen && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-md p-6 shadow-xl">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-gray-900">Dashboard anpassen</h2>
              <button onClick={() => setIsSettingsOpen(false)} className="text-gray-400 hover:text-gray-600">
                <X size={20} />
              </button>
            </div>
            <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 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' && 'Projekt-Counter'}
                    {id === 'chart' && 'Zeit-Chart'}
                    {id === 'activityFeed' && 'Aktivitäts-Feed'}
                  </span>
                  <input 
                    type="checkbox" 
                    checked={visibleWidgets[id]} 
                    onChange={(e) => saveWidgets({ ...visibleWidgets, [id]: e.target.checked })}
                    className="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
                  />
                </label>
              ))}
            </div>
            <button 
              onClick={() => setIsSettingsOpen(false)}
              className="w-full mt-8 py-2 bg-indigo-600 text-white rounded-lg font-semibold hover:bg-indigo-700 transition-colors"
            >
              Fertig
            </button>
          </div>
        </div>
      )}
    </div>
  )
}