import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Home, Users, Copy, RefreshCw, LogOut, X, Check } from 'lucide-react'
import {
  getMyHousehold,
  createHousehold,
  joinHousehold,
  leaveHousehold,
  regenerateInviteCode,
  type Household,
} from '../../api/households'
import { useAuth } from '../../context/AuthContext'
import { showToast } from '../../utils/toast'

export function HouseholdCard() {
  const { user } = useAuth()
  const qc = useQueryClient()
  const [showCreate, setShowCreate] = useState(false)
  const [showJoin, setShowJoin] = useState(false)
  const [showLeaveConfirm, setShowLeaveConfirm] = useState(false)
  const [name, setName] = useState('')
  const [code, setCode] = useState('')
  const [copied, setCopied] = useState(false)

  const { data: household, isLoading } = useQuery({
    queryKey: ['household'],
    queryFn: async () => {
      try {
        const res = await getMyHousehold()
        return res.data as Household
      } catch {
        // 404 = no household, that's fine
        return null
      }
    },
    retry: false,
  })

  const myRole = household?.members.find((m) => m.user_id === user?.id)?.role

  const createMut = useMutation({
    mutationFn: (n: string) => createHousehold(n),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['household'] })
      setShowCreate(false)
      setName('')
      showToast.success('Haushalt erstellt! 🏠')
    },
    onError: (err: Error) => showToast.error(err.message),
  })

  const joinMut = useMutation({
    mutationFn: (c: string) => joinHousehold(c),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['household'] })
      setShowJoin(false)
      setCode('')
      showToast.success('Haushalt beigetreten! 🎉')
    },
    onError: (err: Error) => showToast.error(err.message),
  })

  const leaveMut = useMutation({
    mutationFn: () => leaveHousehold(household!.id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['household'] })
      setShowLeaveConfirm(false)
      showToast.success('Haushalt verlassen')
    },
    onError: (err: Error) => showToast.error(err.message),
  })

  const regenMut = useMutation({
    mutationFn: () => regenerateInviteCode(household!.id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['household'] })
      showToast.success('Neuer Code generiert')
    },
    onError: (err: Error) => showToast.error(err.message),
  })

  // Clipboard fallback for HTTP (no navigator.clipboard)
  const copyCode = () => {
    if (!household?.invite_code) return
    try {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(household.invite_code)
      } else {
        // Fallback: textarea trick
        const ta = document.createElement('textarea')
        ta.value = household.invite_code
        ta.style.position = 'fixed'
        ta.style.left = '-9999px'
        document.body.appendChild(ta)
        ta.select()
        document.execCommand('copy')
        document.body.removeChild(ta)
      }
      setCopied(true)
      showToast.success('Code kopiert!')
      setTimeout(() => setCopied(false), 2000)
    } catch {
      // Last resort: show code in prompt
      showToast.error('Kopiere den Code manuell: ' + household.invite_code)
    }
  }

  if (isLoading) {
    return <div className="bg-surface rounded-2xl p-4 shadow-sm animate-pulse h-24" />
  }

  // No household
  if (!household) {
    return (
      <>
        <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">
            <Home size={16} className="text-primary" />
            Haushalt
          </div>
          <p className="text-sm text-warm-grey mb-4">
            Teile deine Einkaufsliste mit deiner Familie
          </p>
          <div className="space-y-2">
            <button
              onClick={() => setShowCreate(true)}
              className="w-full bg-primary text-white rounded-xl py-3 font-medium min-h-[44px] transition-opacity hover:opacity-90"
            >
              Haushalt erstellen
            </button>
            <button
              onClick={() => setShowJoin(true)}
              className="w-full border border-sand text-espresso rounded-xl py-3 font-medium min-h-[44px] transition-colors hover:bg-sand/30"
            >
              Mit Code beitreten
            </button>
          </div>
        </div>

        {/* Create Modal */}
        {showCreate && (
          <div
            className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 backdrop-blur-sm"
            onClick={() => setShowCreate(false)}
          >
            <div
              className="bg-cream w-full sm:max-w-sm sm:rounded-2xl rounded-t-2xl p-6"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-display text-lg text-espresso">Haushalt erstellen</h3>
                <button onClick={() => setShowCreate(false)} className="min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey">
                  <X size={20} />
                </button>
              </div>
              <form onSubmit={(e) => { e.preventDefault(); name.trim() && createMut.mutate(name.trim()) }}>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="z.B. Luna & Marc"
                  autoFocus
                  className="w-full bg-surface border border-sand rounded-xl px-4 py-3 text-espresso placeholder:text-warm-grey/50 focus:outline-none focus:ring-2 focus:ring-primary/30 min-h-[44px] mb-4"
                />
                <button
                  type="submit"
                  disabled={!name.trim() || createMut.isPending}
                  className="w-full bg-primary text-white rounded-xl py-3 font-medium min-h-[44px] disabled:opacity-50"
                >
                  {createMut.isPending ? 'Erstellen...' : 'Erstellen'}
                </button>
              </form>
            </div>
          </div>
        )}

        {/* Join Modal */}
        {showJoin && (
          <div
            className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 backdrop-blur-sm"
            onClick={() => setShowJoin(false)}
          >
            <div
              className="bg-cream w-full sm:max-w-sm sm:rounded-2xl rounded-t-2xl p-6"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-display text-lg text-espresso">Mit Code beitreten</h3>
                <button onClick={() => setShowJoin(false)} className="min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey">
                  <X size={20} />
                </button>
              </div>
              <form onSubmit={(e) => { e.preventDefault(); code.trim() && joinMut.mutate(code.trim()) }}>
                <input
                  type="text"
                  value={code}
                  onChange={(e) => setCode(e.target.value.toUpperCase())}
                  placeholder="Einladungscode"
                  autoFocus
                  autoCapitalize="characters"
                  className="w-full bg-surface border border-sand rounded-xl px-4 py-3 text-espresso font-mono tracking-wider placeholder:text-warm-grey/50 placeholder:font-sans placeholder:tracking-normal focus:outline-none focus:ring-2 focus:ring-primary/30 min-h-[44px] mb-4"
                />
                <button
                  type="submit"
                  disabled={!code.trim() || joinMut.isPending}
                  className="w-full bg-primary text-white rounded-xl py-3 font-medium min-h-[44px] disabled:opacity-50"
                >
                  {joinMut.isPending ? 'Beitreten...' : 'Beitreten'}
                </button>
              </form>
            </div>
          </div>
        )}
      </>
    )
  }

  // Has household
  return (
    <>
      <div className="bg-surface rounded-2xl p-4 shadow-sm">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2 text-espresso font-medium text-sm">
            <Home size={16} className="text-primary" />
            Haushalt
          </div>
          <span className="flex items-center gap-1 text-xs text-warm-grey">
            <Users size={14} /> {household.members.length}
          </span>
        </div>

        <h3 className="font-display text-lg text-espresso mb-3">{household.name}</h3>

        {/* Members */}
        <div className="space-y-2 mb-4">
          {household.members.map((m) => (
            <div key={m.user_id} className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-primary-light flex items-center justify-center text-sm">
                {m.avatar_url ? (
                  <img src={m.avatar_url} alt={m.display_name} className="w-full h-full rounded-full object-cover" />
                ) : (
                  <span className="text-primary font-medium">
                    {m.display_name.charAt(0).toUpperCase()}
                  </span>
                )}
              </div>
              <span className="text-sm text-espresso flex-1">{m.display_name}</span>
              {m.role === 'owner' && (
                <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">
                  Admin
                </span>
              )}
            </div>
          ))}
        </div>

        {/* Invite code (owner only) */}
        {myRole === 'owner' && (
          <div className="bg-sand/30 rounded-xl p-3 mb-3">
            <p className="text-xs text-warm-grey mb-1">Einladungscode</p>
            <div className="flex items-center gap-2">
              <code className="flex-1 text-sm font-mono text-espresso bg-surface rounded-lg px-3 py-2 select-all">
                {household.invite_code}
              </code>
              <button
                onClick={copyCode}
                className="min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey hover:text-primary transition-colors"
                title="Code kopieren"
              >
                {copied ? <Check size={18} className="text-sage" /> : <Copy size={18} />}
              </button>
              <button
                onClick={() => regenMut.mutate()}
                disabled={regenMut.isPending}
                className="min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey hover:text-primary transition-colors disabled:opacity-50"
                title="Neuen Code generieren"
              >
                <RefreshCw size={18} className={regenMut.isPending ? 'animate-spin' : ''} />
              </button>
            </div>
          </div>
        )}

        {/* Actions */}
        {myRole === 'member' && (
          <button
            onClick={() => setShowLeaveConfirm(true)}
            className="w-full flex items-center justify-center gap-2 border border-berry-red/30 text-berry-red rounded-xl py-3 font-medium min-h-[44px] transition-colors hover:bg-berry-red/5"
          >
            <LogOut size={16} />
            Haushalt verlassen
          </button>
        )}
      </div>

      {/* Leave confirm */}
      {showLeaveConfirm && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm px-6"
          onClick={() => setShowLeaveConfirm(false)}
        >
          <div
            className="bg-surface rounded-2xl p-6 max-w-sm w-full shadow-xl"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="font-display text-lg text-espresso mb-2">Haushalt verlassen?</h3>
            <p className="text-warm-grey text-sm mb-5">
              Du verlierst Zugriff auf die gemeinsame Einkaufsliste.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowLeaveConfirm(false)}
                className="flex-1 py-3 rounded-xl border border-sand text-espresso font-medium min-h-[44px]"
              >
                Abbrechen
              </button>
              <button
                onClick={() => leaveMut.mutate()}
                disabled={leaveMut.isPending}
                className="flex-1 py-3 rounded-xl bg-berry-red text-white font-medium min-h-[44px] disabled:opacity-50"
              >
                {leaveMut.isPending ? 'Wird verlassen...' : 'Verlassen'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
