"use client"

import { useEffect, useCallback } from "react"
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
import { ULTICARDS_APP_NAME } from "@/lib/suite/page-metadata"
import { useContactsStore } from "@/lib/contacts/contacts-store"
import { ContactsListView } from "./contacts-list-view"
import { ContactFormView } from "./contact-form-view"
import { ContactDetailView } from "./contact-detail-view"

export function ContactsPanel() {
  const { panelOpen, view, activeContactId, closePanel, setSearchMode, setSearchQuery, searchMode } =
    useContactsStore()

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (!panelOpen || view !== "list" || searchMode) return
      if (e.metaKey || e.ctrlKey || e.altKey) return
      const target = e.target as HTMLElement
      if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) return
      if (e.key.length === 1 && /\S/.test(e.key)) {
        e.preventDefault()
        setSearchMode(true)
        setSearchQuery(e.key)
      }
    },
    [panelOpen, view, searchMode, setSearchMode, setSearchQuery],
  )

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown)
    return () => document.removeEventListener("keydown", handleKeyDown)
  }, [handleKeyDown])

  return (
    <Sheet open={panelOpen} onOpenChange={(open) => !open && closePanel()}>
      <SheetContent
        side="right"
        hideClose
        overlayClassName="bg-transparent"
        data-contacts-panel
        className="w-[360px] sm:max-w-[360px] gap-0 border-border bg-mail-surface p-0 text-foreground"
      >
        <SheetTitle className="sr-only">{ULTICARDS_APP_NAME}</SheetTitle>
        {view === "list" && <ContactsListView />}
        {view === "view" && <ContactDetailView contactId={activeContactId} />}
        {view === "create" && <ContactFormView mode="create" />}
        {view === "edit" && <ContactFormView mode="edit" contactId={activeContactId} />}
      </SheetContent>
    </Sheet>
  )
}
