import { useState, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Trash2, Plus, X } from 'lucide-react'
import {
  fetchShopping,
  addCustomItem,
  toggleCheck,
  deleteItem,
  deleteChecked,
  deleteAll,
} from '../api/shopping'
import type { ShoppingGroup, ShoppingItem } from '../api/shopping'
import { useAuth } from '../context/AuthContext'
import { EmptyState } from '../components/ui/EmptyState'

export function ShoppingPage() {
  const qc = useQueryClient()
  const { isAuthenticated } = useAuth()
  const [newItem, setNewItem] = useState('')
  const [scope, setScope] = useState<'personal' | 'household'>('personal')
  const inputRef = useRef<HTMLInputElement>(null)

  // Check if user has a household
  const { data: householdData } = useQuery({
    queryKey: ['household'],
    enabled: isAuthenticated,
    retry: false,
  })
  const hasHousehold = !!householdData?.data

  const activeScope = hasHousehold ? scope : undefined

  const { data: groups = [], isLoading, refetch } = useQuery({
    queryKey: ['shopping', activeScope],
    queryFn: () => fetchShopping(activeScope),
  })

  const checkMutation = useMutation({
    mutationFn: toggleCheck,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['shopping'] }),
  })

  const deleteMutation = useMutation({
    mutationFn: deleteItem,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['shopping'] }),
  })

  const deleteCheckedMutation = useMutation({
    mutationFn: () => deleteChecked(activeScope),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['shopping'] }),
  })

  const deleteAllMutation = useMutation({
    mutationFn: () => deleteAll(activeScope),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['shopping'] }),
  })

  const [showClearConfirm, setShowClearConfirm] = useState(false)

  const addMutation = useMutation({
    mutationFn: (item: { name: string }) => addCustomItem(item, activeScope),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['shopping'] })
      setNewItem('')
      inputRef.current?.focus()
    },
  })

  const handleAdd = () => {
    const name = newItem.trim()
    if (!name) return
    addMutation.mutate({ name })
  }

  const hasChecked = groups.some((g) => g.items.some((i) => i.checked))
  const totalItems = groups.reduce((acc, g) => acc + g.items.length, 0)
  const totalChecked = groups.reduce((acc, g) => acc + g.items.filter((i) => i.checked).length, 0)
  const totalUnchecked = totalItems - totalChecked
  const recipeCount = groups.filter((g) => g.recipe_id).length

  const sortItems = (items: ShoppingItem[]) => {
    const unchecked = items.filter((i) => !i.checked)
    const checked = items.filter((i) => i.checked)
    return [...unchecked, ...checked]
  }

  const [pulling, setPulling] = useState(false)
  const touchStartY = useRef(0)

  const handleTouchStart = (e: React.TouchEvent) => {
    if (window.scrollY === 0) touchStartY.current = e.touches[0].clientY
  }

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (pulling) {
      const dy = e.changedTouches[0].clientY - touchStartY.current
      if (dy > 80) refetch()
      setPulling(false)
    }
  }

  const handleTouchMove = (e: React.TouchEvent) => {
    if (window.scrollY === 0) {
      const dy = e.touches[0].clientY - touchStartY.current
      if (dy > 30) setPulling(true)
    }
  }

  if (isLoading) {
    return (
      <div className="p-4 space-y-4">
        {[1, 2, 3].map((i) => (
          <div key={i} className="bg-surface rounded-2xl p-4 animate-pulse h-20" />
        ))}
      </div>
    )
  }

  return (
    <div
      className="min-h-screen"
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      {/* TopBar */}
      <div className="sticky top-0 z-40 bg-cream/95 backdrop-blur-sm border-b border-sand px-4 py-3 flex items-center justify-between">
        <h1 className="font-display text-xl text-espresso">Einkaufsliste</h1>
        <div className="flex items-center gap-2">
          {totalUnchecked > 0 && (
            <span className="text-sm text-warm-grey">{totalUnchecked} offen</span>
          )}
          {hasChecked && (
            <button
              onClick={() => deleteCheckedMutation.mutate()}
              className="p-2 text-warm-grey hover:text-berry-red transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
              title="Erledigte löschen"
            >
              <Trash2 size={18} />
            </button>
          )}
          {totalItems > 0 && (
            <button
              onClick={() => setShowClearConfirm(true)}
              className="p-2 text-warm-grey hover:text-berry-red transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
              title="Alles löschen"
            >
              <Trash2 size={20} className="text-berry-red/70" />
            </button>
          )}
        </div>
      </div>

      {/* Scope Toggle */}
      {hasHousehold && (
        <div className="sticky top-[53px] z-35 bg-cream/95 backdrop-blur-sm px-4 py-2">
          <div className="flex bg-sand/50 rounded-xl p-1">
            <button
              onClick={() => setScope('personal')}
              className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors min-h-[36px] ${
                scope === 'personal'
                  ? 'bg-primary text-white'
                  : 'text-warm-grey hover:text-espresso'
              }`}
            >
              Persönlich
            </button>
            <button
              onClick={() => setScope('household')}
              className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors min-h-[36px] ${
                scope === 'household'
                  ? 'bg-primary text-white'
                  : 'text-warm-grey hover:text-espresso'
              }`}
            >
              🏠 Haushalt
            </button>
          </div>
        </div>
      )}

      {/* Clear All Confirm */}
      {showClearConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm px-6">
          <div className="bg-surface rounded-2xl p-6 max-w-sm w-full shadow-xl">
            <h3 className="font-display text-lg text-espresso mb-2">Einkaufsliste leeren?</h3>
            <p className="text-warm-grey text-sm mb-5">Alle Artikel werden unwiderruflich gelöscht.</p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowClearConfirm(false)}
                className="flex-1 py-3 rounded-xl border border-sand text-espresso font-medium min-h-[44px]"
              >
                Abbrechen
              </button>
              <button
                onClick={() => {
                  deleteAllMutation.mutate()
                  setShowClearConfirm(false)
                }}
                className="flex-1 py-3 rounded-xl bg-berry-red text-white font-medium min-h-[44px]"
              >
                🗑️ Alles löschen
              </button>
            </div>
          </div>
        </div>
      )}

      {pulling && (
        <div className="text-center text-warm-grey text-sm py-2">↓ Loslassen zum Aktualisieren</div>
      )}

      {/* Quick-Add */}
      <div className={`sticky ${hasHousehold ? 'top-[105px]' : 'top-[53px]'} z-30 bg-cream/95 backdrop-blur-sm px-4 py-3`}>
        <form
          onSubmit={(e) => {
            e.preventDefault()
            handleAdd()
          }}
          className="flex gap-2"
        >
          <input
            ref={inputRef}
            type="text"
            value={newItem}
            onChange={(e) => setNewItem(e.target.value)}
            placeholder="Artikel hinzufügen..."
            className="flex-1 bg-surface border border-sand rounded-xl px-4 py-3 text-base sm:text-lg text-espresso placeholder:text-warm-grey/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
          />
          <button
            type="submit"
            disabled={!newItem.trim() || addMutation.isPending}
            className="bg-primary text-white rounded-xl px-4 py-3 min-w-[44px] min-h-[44px] flex items-center justify-center disabled:opacity-40 transition-opacity"
          >
            <Plus size={20} />
          </button>
        </form>
      </div>

      {/* Summary */}
      {totalItems > 0 && (
        <div className="px-4 pb-2">
          <div className="bg-primary-light/30 rounded-2xl p-3">
            <div className="flex items-center justify-between text-sm text-espresso">
              <span>
                {recipeCount > 0 && <>{recipeCount} Rezept{recipeCount !== 1 ? 'e' : ''} · </>}
                {totalItems} Artikel · {totalChecked} erledigt
              </span>
              <span className="text-warm-grey text-xs">
                {totalItems > 0 ? Math.round((totalChecked / totalItems) * 100) : 0}%
              </span>
            </div>
            <div className="mt-2 h-1.5 bg-sand rounded-full overflow-hidden">
              <div
                className="h-full bg-primary rounded-full transition-all duration-300"
                style={{ width: `${totalItems > 0 ? (totalChecked / totalItems) * 100 : 0}%` }}
              />
            </div>
          </div>
        </div>
      )}

      {/* Content */}
      <div className="px-4 pb-24 space-y-4">
        {groups.length === 0 ? (
          <EmptyState
            icon="🛒"
            title="Einkaufsliste leer"
            description="Füge Zutaten aus einem Rezept hinzu oder erstelle eigene Einträge."
          />
        ) : (
          groups.map((group) => (
            <div key={group.recipe_title} className="bg-surface rounded-2xl shadow-sm overflow-hidden">
              <div className="px-4 py-3 border-b border-sand/50 flex items-center gap-2">
                <span className="text-base">{group.recipe_id ? '🍰' : '📝'}</span>
                <h3 className="font-semibold text-sm text-espresso truncate">
                  {group.recipe_title || 'Eigene'}
                </h3>
                <span className="text-xs text-warm-grey ml-auto">
                  {group.items.filter((i) => !i.checked).length}/{group.items.length}
                </span>
              </div>
              <ul>
                {sortItems(group.items).map((item) => (
                  <ShoppingItemRow
                    key={item.id}
                    item={item}
                    onToggle={() => checkMutation.mutate(item.id)}
                    onDelete={() => deleteMutation.mutate(item.id)}
                  />
                ))}
              </ul>
            </div>
          ))
        )}
      </div>
    </div>
  )
}

function ShoppingItemRow({
  item,
  onToggle,
  onDelete,
}: {
  item: ShoppingItem
  onToggle: () => void
  onDelete: () => void
}) {
  const THRESHOLD = -80
  const [swipeX, setSwipeX] = useState(0)
  const touchStartX = useRef(0)
  const swiping = useRef(false)
  const pastThreshold = swipeX < THRESHOLD

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
    swiping.current = false
  }

  const handleTouchMove = (e: React.TouchEvent) => {
    const dx = e.touches[0].clientX - touchStartX.current
    if (dx < -10) {
      swiping.current = true
      setSwipeX(Math.max(dx, -160))
    } else {
      setSwipeX(0)
    }
  }

  const handleTouchEnd = () => {
    if (pastThreshold) {
      setSwipeX(-300)
      setTimeout(() => onDelete(), 200)
    } else {
      setSwipeX(0)
    }
    swiping.current = false
  }

  const amountText = [item.amount, item.unit].filter(Boolean).join(' ')

  return (
    <li className="relative overflow-hidden">
      <div
        className={`absolute inset-y-0 right-0 w-40 flex items-center justify-center transition-colors ${
          pastThreshold ? 'bg-berry-red' : 'bg-berry-red/60'
        }`}
      >
        <span
          className={`text-white font-medium transition-all ${
            pastThreshold ? 'text-sm scale-110' : 'text-xs'
          }`}
        >
          {pastThreshold ? '🗑️ Löschen' : '×'}
        </span>
      </div>

      <div
        className={`relative bg-surface flex items-center gap-3 px-4 min-h-[52px] ${
          swiping.current ? '' : 'transition-transform duration-200'
        }`}
        style={{ transform: `translateX(${swipeX}px)` }}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        <button
          onClick={onToggle}
          className="flex-shrink-0 w-6 h-6 rounded-md border-2 flex items-center justify-center transition-colors min-w-[44px] min-h-[44px]"
          style={{
            borderColor: item.checked ? '#C4737E' : '#E8E0D8',
            backgroundColor: item.checked ? '#C4737E' : 'transparent',
          }}
        >
          {item.checked && (
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path
                d="M2.5 7L5.5 10L11.5 4"
                stroke="white"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          )}
        </button>

        <div className={`flex-1 min-w-0 ${item.checked ? 'opacity-50' : ''}`}>
          <span
            className={`text-base sm:text-lg text-espresso ${
              item.checked ? 'line-through text-warm-grey' : ''
            }`}
          >
            {item.name}
          </span>
        </div>

        {amountText && (
          <span
            className={`text-sm flex-shrink-0 ${
              item.checked ? 'text-warm-grey/50 line-through' : 'text-warm-grey'
            }`}
          >
            {amountText}
          </span>
        )}
      </div>
    </li>
  )
}
