import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { motion } from 'framer-motion'
import { Link } from 'react-router'
import { fetchRecipes } from '../api/recipes'
import { fetchShopping } from '../api/shopping'
import { LogOut, Info, Heart, BookOpen, ShoppingCart, Settings, User, ChevronRight } from 'lucide-react'
import { useAuth } from '../context/AuthContext'
import { EmptyState } from '../components/ui/EmptyState'
import { Button } from '../components/ui/Button'
import { EditProfileModal } from '../components/profile/EditProfileModal'
import { ChangePasswordModal } from '../components/profile/ChangePasswordModal'
import { HouseholdCard } from '../components/profile/HouseholdCard'
import { showToast } from '../utils/toast'

export function ProfilePage() {
  const { user, isAuthenticated, logout, isLoading } = useAuth()
  const [showEditProfile, setShowEditProfile] = useState(false)
  const [showChangePassword, setShowChangePassword] = useState(false)

  const { data: allRecipes } = useQuery({
    queryKey: ['recipes', {}],
    queryFn: () => fetchRecipes({}),
  })

  const { data: favRecipes } = useQuery({
    queryKey: ['recipes', { favorite: true }],
    queryFn: () => fetchRecipes({ favorite: true }),
  })

  const { data: shoppingGroups } = useQuery({
    queryKey: ['shopping'],
    queryFn: () => fetchShopping(),
  })

  const totalRecipes = allRecipes?.total ?? 0
  const totalFavorites = favRecipes?.total ?? 0
  const totalShoppingItems = (shoppingGroups ?? []).reduce((acc, g) => acc + g.items.length, 0)

  const stats = [
    { icon: <BookOpen size={18} />, label: 'Rezepte', value: totalRecipes },
    { icon: <Heart size={18} />, label: 'Favoriten', value: totalFavorites },
    { icon: <ShoppingCart size={18} />, label: 'Einkauf', value: totalShoppingItems },
  ]

  const handleLogout = async () => {
    try {
      await logout()
      showToast.success('Erfolgreich abgemeldet')
    } catch (error) {
      console.error('Logout failed:', error)
      showToast.error('Abmeldung fehlgeschlagen')
    }
  }

  if (!isLoading && !isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <EmptyState
          icon="🔐"
          title="Anmeldung erforderlich"
          description="Melde dich an, um dein Profil zu verwalten"
        />
        <div className="absolute bottom-32 left-1/2 transform -translate-x-1/2 space-y-3 w-full max-w-sm px-4">
          <Link to="/login">
            <Button className="w-full min-h-[44px]">Anmelden</Button>
          </Link>
          <Link to="/register">
            <Button variant="ghost" className="w-full min-h-[44px]">Registrieren</Button>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pb-24">
      {/* Avatar & Name */}
      <div className="px-4 py-6 text-center">
        <motion.div
          className="w-20 h-20 rounded-full bg-primary-light flex items-center justify-center text-3xl mx-auto mb-3"
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
        >
          {user?.avatar_url ? (
            <img
              src={user.avatar_url}
              alt={user.display_name}
              className="w-full h-full rounded-full object-cover"
            />
          ) : (
            <User size={28} className="text-primary" />
          )}
        </motion.div>
        <h1 className="font-display text-2xl text-espresso">
          {user?.display_name || 'Benutzer'}
        </h1>
        <p className="text-sm text-warm-grey mt-1">{user?.email}</p>
      </div>

      {/* Profil verwalten */}
      <div className="px-4 pb-4">
        <div className="bg-surface rounded-2xl p-4 shadow-sm space-y-1">
          <div className="flex items-center gap-2 text-espresso font-medium text-sm mb-3">
            <Settings size={16} className="text-primary" />
            Profil verwalten
          </div>
          <button
            onClick={() => setShowEditProfile(true)}
            className="w-full flex items-center justify-between p-3 rounded-xl hover:bg-sand/30 transition-colors min-h-[44px]"
          >
            <span className="text-sm text-espresso">Profil bearbeiten</span>
            <ChevronRight size={16} className="text-warm-grey" />
          </button>
          <button
            onClick={() => setShowChangePassword(true)}
            className="w-full flex items-center justify-between p-3 rounded-xl hover:bg-sand/30 transition-colors min-h-[44px]"
          >
            <span className="text-sm text-espresso">Passwort ändern</span>
            <ChevronRight size={16} className="text-warm-grey" />
          </button>
        </div>
      </div>

      {/* Haushalt */}
      <div className="px-4 pb-4">
        <HouseholdCard />
      </div>

      {/* Stats */}
      <div className="px-4 pb-4">
        <div className="grid grid-cols-3 gap-3">
          {stats.map((stat) => (
            <motion.div
              key={stat.label}
              className="bg-surface rounded-2xl p-4 text-center shadow-sm"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
            >
              <div className="flex justify-center text-primary mb-1">{stat.icon}</div>
              <div className="font-display text-xl text-espresso">{stat.value}</div>
              <div className="text-xs text-warm-grey">{stat.label}</div>
            </motion.div>
          ))}
        </div>
      </div>

      {/* App Info */}
      <div className="px-4 pb-4">
        <div className="bg-surface rounded-2xl p-4 shadow-sm">
          <div className="flex items-center gap-2 text-espresso font-medium text-sm mb-3">
            <Info size={16} className="text-primary" />
            App-Info
          </div>
          <div className="text-sm text-warm-grey space-y-1">
            <div className="flex justify-between">
              <span>Version</span>
              <span className="text-espresso">2.1.2026</span>
            </div>
            <div className="flex justify-between">
              <span>Erstellt</span>
              <span className="text-espresso">Made with 💕 by Moldi</span>
            </div>
          </div>
        </div>
      </div>

      {/* Logout */}
      <div className="px-4 pb-8">
        <button
          onClick={handleLogout}
          className="w-full flex items-center justify-center gap-2 bg-berry-red text-white px-4 py-3 rounded-xl font-medium text-sm hover:bg-berry-red/90 transition-colors min-h-[44px]"
        >
          <LogOut size={18} />
          Abmelden
        </button>
      </div>

      {/* Modals */}
      <EditProfileModal open={showEditProfile} onClose={() => setShowEditProfile(false)} />
      <ChangePasswordModal open={showChangePassword} onClose={() => setShowChangePassword(false)} />
    </div>
  )
}
