"use client"

import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent,
} from "react"
import { useRouter } from "next/navigation"
import {
  ArrowLeft,
  Search,
  X,
  Paperclip,
  Clock,
  User,
  SlidersHorizontal,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { cn } from "@/lib/utils"
import { emails } from "@/lib/email-data"
import { useContactsStore } from "@/lib/contacts/contacts-store"
import { useActiveAccount } from "@/lib/stores/account-store"
import {
  matchContacts,
  matchEmails,
  bestCompletion,
  type SearchSuggestion,
} from "@/lib/mail-search/search-engine"
import {
  buildSearchUrl,
  EMPTY_SEARCH_PARAMS,
  DATE_RANGE_OPTIONS,
  SEARCH_IN_OPTIONS,
  type SearchParams,
} from "@/lib/mail-search/search-params"
import { avatarColor, senderInitial } from "@/lib/sender-display"

interface MobileSearchOverlayProps {
  open: boolean
  onClose: () => void
  initialQuery?: string
}

export function MobileSearchOverlay({ open, onClose, initialQuery = "" }: MobileSearchOverlayProps) {
  const router = useRouter()
  const account = useActiveAccount()
  const contacts = useContactsStore((s) => s.contacts)

  const [inputValue, setInputValue] = useState(initialQuery)
  const [selectedIndex, setSelectedIndex] = useState(-1)
  const [chipAttachment, setChipAttachment] = useState(false)
  const [chipLast7Days, setChipLast7Days] = useState(false)
  const [chipFromMe, setChipFromMe] = useState(false)
  const [advancedMode, setAdvancedMode] = useState(false)

  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (open) {
      setInputValue(initialQuery)
      setAdvancedMode(false)
      setTimeout(() => inputRef.current?.focus(), 50)
    } else {
      setSelectedIndex(-1)
      setChipAttachment(false)
      setChipLast7Days(false)
      setChipFromMe(false)
      setAdvancedMode(false)
    }
  }, [open, initialQuery])

  const suggestions = useMemo<SearchSuggestion[]>(() => {
    if (!inputValue.trim()) return []
    const contactHits = matchContacts(inputValue, contacts, 4)
    const emailHits = matchEmails(inputValue, emails, 4)
    const seen = new Set(contactHits.map((c) => c.email))
    const unique = emailHits.filter((e) => !seen.has(e.email))
    return [...contactHits, ...unique]
  }, [inputValue, contacts])

  const ghostText = useMemo(
    () => bestCompletion(inputValue, suggestions),
    [inputValue, suggestions]
  )

  const totalItems = suggestions.length + 1

  const submitSearch = useCallback(
    (overrideQuery?: string) => {
      const q = overrideQuery ?? inputValue
      if (!q.trim() && !chipAttachment && !chipLast7Days && !chipFromMe) return
      const params: Partial<SearchParams> = { q: q.trim() }
      if (chipAttachment) params.has = ["attachment"]
      if (chipLast7Days) params.within = "1w"
      if (chipFromMe) params.from = account.email
      router.push(buildSearchUrl(params))
      onClose()
    },
    [inputValue, chipAttachment, chipLast7Days, chipFromMe, account.email, router, onClose]
  )

  const selectSuggestion = useCallback(
    (s: SearchSuggestion) => {
      const params: Partial<SearchParams> = { q: s.email }
      if (chipAttachment) params.has = ["attachment"]
      if (chipLast7Days) params.within = "1w"
      if (chipFromMe) params.from = account.email
      router.push(buildSearchUrl(params))
      onClose()
    },
    [chipAttachment, chipLast7Days, chipFromMe, account.email, router, onClose]
  )

  const handleKeyDown = useCallback(
    (e: KeyboardEvent<HTMLInputElement>) => {
      switch (e.key) {
        case "ArrowDown":
          e.preventDefault()
          setSelectedIndex((i) => (i < totalItems - 1 ? i + 1 : 0))
          break
        case "ArrowUp":
          e.preventDefault()
          setSelectedIndex((i) => (i > 0 ? i - 1 : totalItems - 1))
          break
        case "Enter":
          e.preventDefault()
          if (selectedIndex >= 0 && selectedIndex < suggestions.length) {
            selectSuggestion(suggestions[selectedIndex]!)
          } else {
            submitSearch()
          }
          break
        case "Tab":
          if (ghostText) {
            e.preventDefault()
            setInputValue(inputValue + ghostText)
          }
          break
        case "Escape":
          e.preventDefault()
          onClose()
          break
      }
    },
    [selectedIndex, totalItems, suggestions, ghostText, inputValue, submitSearch, selectSuggestion, onClose]
  )

  return (
    <Sheet open={open} onOpenChange={(isOpen) => { if (!isOpen) onClose() }}>
      <SheetContent
        side="bottom"
        hideClose
        overlayClassName="z-[100] bg-black/40"
        className={cn(
          "z-[101] flex h-[100dvh] max-h-[100dvh] w-full flex-col gap-0 rounded-none border-0 bg-background p-0 shadow-xl",
          "duration-300 ease-out",
          "data-[state=open]:animate-in data-[state=closed]:animate-out",
          "data-[state=open]:slide-in-from-bottom data-[state=closed]:slide-out-to-bottom",
          "pb-[env(safe-area-inset-bottom)]"
        )}
      >
        <SheetTitle className="sr-only">Rechercher dans les messages</SheetTitle>
      {/* Header */}
      <div className="flex shrink-0 items-center gap-2 border-b border-gray-200 px-2 py-2 dark:border-gray-800">
        <Button
          variant="ghost"
          size="icon"
          className="size-10 shrink-0 text-gray-600"
          onClick={() => { if (advancedMode) setAdvancedMode(false); else onClose() }}
          aria-label="Retour"
        >
          <ArrowLeft className="size-5" />
        </Button>
        <div className="relative flex min-w-0 flex-1 items-center">
          {ghostText && !advancedMode && (
            <div className="pointer-events-none absolute left-0 flex items-center text-sm text-gray-400" aria-hidden>
              <span className="invisible">{inputValue}</span>
              <span>{ghostText}</span>
            </div>
          )}
          <input
            ref={inputRef}
            type="text"
            value={inputValue}
            onChange={(e) => {
              setInputValue(e.target.value)
              setSelectedIndex(-1)
              if (advancedMode) setAdvancedMode(false)
            }}
            onKeyDown={handleKeyDown}
            placeholder="Rechercher dans les messages"
            className="h-10 w-full bg-transparent text-sm outline-none placeholder:text-gray-400"
            autoComplete="off"
          />
        </div>
        {inputValue && !advancedMode && (
          <Button
            variant="ghost"
            size="icon"
            className="size-10 shrink-0 text-gray-600"
            onClick={() => {
              setInputValue("")
              inputRef.current?.focus()
            }}
            aria-label="Effacer"
          >
            <X className="size-5" />
          </Button>
        )}
        <Button
          variant="ghost"
          size="icon"
          className="size-10 shrink-0 text-gray-600"
          onClick={() => setAdvancedMode(!advancedMode)}
          aria-label="Recherche avancée"
        >
          <SlidersHorizontal className="size-5" />
        </Button>
      </div>

      {advancedMode ? (
        <MobileAdvancedSearch
          initialQuery={inputValue}
          onSubmit={(url) => { router.push(url); onClose() }}
        />
      ) : (
        <>
          {/* Filter chips */}
          <div className="flex items-center gap-2 overflow-x-auto border-b border-gray-100 px-4 py-2 dark:border-gray-800">
            <button
              type="button"
              onClick={() => setChipAttachment(!chipAttachment)}
              className={cn(
                "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs transition-colors",
                chipAttachment
                  ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
                  : "border-gray-200 text-gray-600 dark:border-gray-700 dark:text-gray-400"
              )}
            >
              <Paperclip className="size-3.5" />
              Contient une pièce jointe
            </button>
            <button
              type="button"
              onClick={() => setChipLast7Days(!chipLast7Days)}
              className={cn(
                "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs transition-colors",
                chipLast7Days
                  ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
                  : "border-gray-200 text-gray-600 dark:border-gray-700 dark:text-gray-400"
              )}
            >
              <Clock className="size-3.5" />
              7 derniers jours
            </button>
            <button
              type="button"
              onClick={() => setChipFromMe(!chipFromMe)}
              className={cn(
                "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs transition-colors",
                chipFromMe
                  ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
                  : "border-gray-200 text-gray-600 dark:border-gray-700 dark:text-gray-400"
              )}
            >
              <User className="size-3.5" />
              De moi
            </button>
          </div>

          {/* Suggestions */}
          <div className="min-h-0 flex-1 overflow-y-auto">
            {inputValue.trim() && (
              <>
                {suggestions.map((s, i) => {
                  const isSelected = i === selectedIndex
                  if (s.kind === "contact") {
                    const initial = senderInitial(s.displayName)
                    const color = avatarColor(s.displayName)
                    return (
                      <button
                        key={`c-${s.contact.id}-${s.email}`}
                        type="button"
                        className={cn(
                          "flex w-full items-center gap-3 px-4 py-3 text-left text-sm active:bg-gray-100 dark:active:bg-gray-800",
                          isSelected && "bg-gray-100 dark:bg-gray-800"
                        )}
                        onClick={() => selectSuggestion(s)}
                      >
                        <div
                          className="flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-medium text-white"
                          style={{ backgroundColor: color }}
                        >
                          {initial}
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="truncate font-medium text-gray-900 dark:text-gray-100">
                            {s.displayName}
                          </div>
                          <div className="truncate text-xs text-gray-500">
                            {s.email}
                          </div>
                        </div>
                      </button>
                    )
                  }
                  return (
                    <button
                      key={`e-${s.email}`}
                      type="button"
                      className={cn(
                        "flex w-full items-center gap-3 px-4 py-3 text-left text-sm active:bg-gray-100 dark:active:bg-gray-800",
                        isSelected && "bg-gray-100 dark:bg-gray-800"
                      )}
                      onClick={() => selectSuggestion(s)}
                    >
                      <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-gray-200 text-gray-500 dark:bg-gray-700">
                        <User className="size-4" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="truncate text-gray-700 dark:text-gray-300">
                          {s.email}
                        </div>
                      </div>
                    </button>
                  )
                })}

                {/* All results row */}
                <button
                  type="button"
                  className={cn(
                    "flex w-full items-center gap-3 px-4 py-3 text-left text-sm active:bg-gray-100 dark:active:bg-gray-800",
                    selectedIndex === suggestions.length && "bg-gray-100 dark:bg-gray-800"
                  )}
                  onClick={() => submitSearch()}
                >
                  <div className="flex size-9 shrink-0 items-center justify-center">
                    <Search className="size-5 text-gray-400" />
                  </div>
                  <span className="text-gray-600 dark:text-gray-400">
                    Tous les résultats pour «&nbsp;
                    <span className="font-medium text-gray-900 dark:text-gray-100">
                      {inputValue}
                    </span>
                    &nbsp;»
                  </span>
                </button>
              </>
            )}
          </div>
        </>
      )}
      </SheetContent>
    </Sheet>
  )
}

// ─── Mobile Advanced Search ──────────────────────────────────────────────────

function MobileAdvancedSearch({
  initialQuery,
  onSubmit,
}: {
  initialQuery: string
  onSubmit: (url: string) => void
}) {
  const [from, setFrom] = useState("")
  const [to, setTo] = useState("")
  const [subject, setSubject] = useState("")
  const [hasWords, setHasWords] = useState(initialQuery)
  const [doesNotHave, setDoesNotHave] = useState("")
  const [sizeVal, setSizeVal] = useState("")
  const [sizeOp, setSizeOp] = useState<"gt" | "lt">("gt")
  const [sizeUnit, setSizeUnit] = useState<"Mo" | "Ko">("Mo")
  const [within, setWithin] = useState("")
  const [searchIn, setSearchIn] = useState("all")
  const [hasAttachment, setHasAttachment] = useState(false)
  const [excludeChats, setExcludeChats] = useState(false)

  const handleSubmit = () => {
    const params: Partial<SearchParams> = {
      ...EMPTY_SEARCH_PARAMS,
      q: "",
      from,
      to,
      subject,
      hasWords,
      doesNotHave,
      size: sizeVal,
      sizeOp,
      sizeUnit,
      within,
      in: searchIn,
      has: hasAttachment ? ["attachment"] : [],
      excludeChats,
    }
    onSubmit(buildSearchUrl(params))
  }

  return (
    <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
      <div className="space-y-4">
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">De</Label>
          <Input value={from} onChange={(e) => setFrom(e.target.value)} className="h-9 text-sm" />
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">À</Label>
          <Input value={to} onChange={(e) => setTo(e.target.value)} className="h-9 text-sm" />
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Objet</Label>
          <Input value={subject} onChange={(e) => setSubject(e.target.value)} className="h-9 text-sm" />
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Contient les mots</Label>
          <Input value={hasWords} onChange={(e) => setHasWords(e.target.value)} className="h-9 text-sm" />
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Ne contient pas</Label>
          <Input value={doesNotHave} onChange={(e) => setDoesNotHave(e.target.value)} className="h-9 text-sm" />
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Taille</Label>
          <div className="flex items-center gap-2">
            <Select value={sizeOp} onValueChange={(v) => setSizeOp(v as "gt" | "lt")}>
              <SelectTrigger className="h-9 flex-1 text-sm">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="gt">supérieure à</SelectItem>
                <SelectItem value="lt">inférieure à</SelectItem>
              </SelectContent>
            </Select>
            <Input
              type="number"
              value={sizeVal}
              onChange={(e) => setSizeVal(e.target.value)}
              className="h-9 w-20 text-sm"
            />
            <Select value={sizeUnit} onValueChange={(v) => setSizeUnit(v as "Mo" | "Ko")}>
              <SelectTrigger className="h-9 w-20 text-sm">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="Mo">Mo</SelectItem>
                <SelectItem value="Ko">Ko</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Plage de dates</Label>
          <Select value={within} onValueChange={setWithin}>
            <SelectTrigger className="h-9 text-sm">
              <SelectValue placeholder="Sélectionner" />
            </SelectTrigger>
            <SelectContent>
              {DATE_RANGE_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs text-gray-500">Rechercher dans</Label>
          <Select value={searchIn} onValueChange={setSearchIn}>
            <SelectTrigger className="h-9 text-sm">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {SEARCH_IN_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-3 pt-1">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
            <Checkbox
              checked={hasAttachment}
              onCheckedChange={(v) => setHasAttachment(v === true)}
            />
            Contenant une pièce jointe
          </label>
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
            <Checkbox
              checked={excludeChats}
              onCheckedChange={(v) => setExcludeChats(v === true)}
            />
            Ne pas inclure les chats
          </label>
        </div>
        <Button
          className="w-full bg-[#1a73e8] text-sm text-white hover:bg-[#1765cc]"
          onClick={handleSubmit}
        >
          Rechercher
        </Button>
      </div>
    </div>
  )
}
