"use client"

import { useEffect, useRef } from "react"
import { Group, Panel, Separator, useDefaultLayout, useGroupRef } from "react-resizable-panels"
import { useUserInterfaceStore } from "@/lib/stores/user-interface-store"
import { useMarkAllAsRead } from "@/lib/queries/use-mark-all-as-read"
import { useSubscriptions } from "@/lib/queries/use-subscriptions"
import { useUnreadCounts } from "@/lib/queries/use-unread-counts"
import { useIsMobile } from "@/lib/hooks/use-is-mobile"
import { classNames } from "@/lib/utilities"
import { EntryList } from "./entry-list"
import { EntryDetailPanel } from "./entry-detail-panel"
import { ErrorBoundary } from "./error-boundary"
import { useRealtimeEntries } from "@/lib/hooks/use-realtime-entries"
import { useCustomFeeds } from "@/lib/queries/use-custom-feeds"

interface ReaderShellProperties {
  userEmailAddress: string | null
  feedFilter: "all" | "saved"
  folderIdentifier?: string | null
  feedIdentifier?: string | null
  customFeedIdentifier?: string | null
}

export function ReaderShell({
  userEmailAddress,
  feedFilter,
  folderIdentifier,
  feedIdentifier,
  customFeedIdentifier,
}: ReaderShellProperties) {
  const selectedEntryIdentifier = useUserInterfaceStore(
    (state) => state.selectedEntryIdentifier
  )
  const setSelectedEntryIdentifier = useUserInterfaceStore(
    (state) => state.setSelectedEntryIdentifier
  )
  const entryListViewMode = useUserInterfaceStore(
    (state) => state.entryListViewMode
  )
  const setEntryListViewMode = useUserInterfaceStore(
    (state) => state.setEntryListViewMode
  )
  const setSearchOpen = useUserInterfaceStore((state) => state.setSearchOpen)
  const markAllAsRead = useMarkAllAsRead()
  const { data: subscriptionsData } = useSubscriptions()
  const { data: unreadCounts } = useUnreadCounts()
  const { data: customFeedsData } = useCustomFeeds()
  const isMobile = useIsMobile()
  const focusedPanel = useUserInterfaceStore((state) => state.focusedPanel)
  const fontSize = useUserInterfaceStore((state) => state.fontSize)
  const toggleShortcutsDialog = useUserInterfaceStore(
    (state) => state.toggleShortcutsDialog
  )

  const detailLayout = useDefaultLayout({
    id: "asa-detail-layout",
    panelIds: ["entry-list", "detail-panel"],
    storage: typeof window !== "undefined" ? localStorage : { getItem: () => null, setItem: () => {} },
  })

  const detailGroupRef = useGroupRef()
  const detailOnLayoutChangedRef = useRef(detailLayout.onLayoutChanged)
  detailOnLayoutChangedRef.current = detailLayout.onLayoutChanged

  useEffect(() => {
    useUserInterfaceStore.getState().setResetDetailLayout(() => {
      const group = detailGroupRef.current
      if (!group) return
      const currentLayout = group.getLayout()
      const panelIdentifiers = Object.keys(currentLayout)
      if (panelIdentifiers.length === 0) return
      const equalSharePercentage = 100 / panelIdentifiers.length
      const equalLayout: Record<string, number> = {}
      for (const panelIdentifier of panelIdentifiers) {
        equalLayout[panelIdentifier] = equalSharePercentage
      }
      const appliedLayout = group.setLayout(equalLayout)
      detailOnLayoutChangedRef.current?.(appliedLayout)
    })
    return () => useUserInterfaceStore.getState().setResetDetailLayout(null)
  }, [detailGroupRef])

  useRealtimeEntries()

  let pageTitle = feedFilter === "saved" ? "saved" : "all entries"

  if (feedFilter === "all" && customFeedIdentifier && customFeedsData) {
    const matchingCustomFeed = customFeedsData.find(
      (customFeed) => customFeed.identifier === customFeedIdentifier
    )

    if (matchingCustomFeed) {
      pageTitle = matchingCustomFeed.name
    }
  }

  if (feedFilter === "all" && feedIdentifier && subscriptionsData) {
    const matchingSubscription = subscriptionsData.subscriptions.find(
      (subscription) => subscription.feedIdentifier === feedIdentifier
    )

    if (matchingSubscription) {
      pageTitle =
        matchingSubscription.customTitle ||
        matchingSubscription.feedTitle ||
        "feed"
    }
  }

  if (feedFilter === "all" && folderIdentifier && subscriptionsData) {
    const matchingFolder = subscriptionsData.folders.find(
      (folder) => folder.folderIdentifier === folderIdentifier
    )

    if (matchingFolder) {
      pageTitle = matchingFolder.name
    }
  }

  const totalUnreadCount = Object.values(unreadCounts ?? {}).reduce(
    (sum, count) => sum + count,
    0
  )
  const allAreRead = totalUnreadCount === 0

  return (
    <div className={classNames(
      "flex h-full flex-col",
      fontSize === "small" ? "text-sm" : fontSize === "large" ? "text-lg" : "text-base"
    )}>
      <header className="flex items-center justify-between border-b border-border px-4 py-3">
        {isMobile && selectedEntryIdentifier ? (
          <button
            type="button"
            onClick={() => setSelectedEntryIdentifier(null)}
            className="text-text-secondary transition-colors hover:text-text-primary"
          >
            &larr; back
          </button>
        ) : (
          <h1 className="text-text-primary">{pageTitle}</h1>
        )}
        <div className="flex items-center gap-3">
          {!(isMobile && selectedEntryIdentifier) && (
            <>
              <button
                type="button"
                onClick={() => setSearchOpen(true)}
                className="text-text-dim transition-colors hover:text-text-secondary"
              >
                search
              </button>
              {feedFilter === "all" && (
                <button
                  type="button"
                  onClick={() =>
                    markAllAsRead.mutate({ readState: !allAreRead })
                  }
                  disabled={markAllAsRead.isPending}
                  className="text-text-dim transition-colors hover:text-text-secondary disabled:opacity-50"
                >
                  {allAreRead ? "mark all unread" : "mark all read"}
                </button>
              )}
              <select
                value={entryListViewMode}
                onChange={(event) =>
                  setEntryListViewMode(
                    event.target.value as "compact" | "comfortable" | "expanded"
                  )
                }
                className="hidden border border-border bg-background-primary px-2 py-1 text-text-secondary outline-none sm:block"
              >
                <option value="compact">compact</option>
                <option value="comfortable">comfortable</option>
                <option value="expanded">expanded</option>
              </select>
              <button
                type="button"
                onClick={() => toggleShortcutsDialog()}
                className="hidden text-text-dim transition-colors hover:text-text-secondary sm:block"
              >
                shortcuts
              </button>
            </>
          )}
        </div>
      </header>
      <ErrorBoundary>
        {isMobile ? (
          selectedEntryIdentifier ? (
            <div className="flex-1 overflow-hidden">
              <ErrorBoundary>
                <EntryDetailPanel
                  entryIdentifier={selectedEntryIdentifier}
                />
              </ErrorBoundary>
            </div>
          ) : (
            <div className="flex-1 overflow-hidden">
              <ErrorBoundary>
                <EntryList
                  feedFilter={feedFilter}
                  folderIdentifier={folderIdentifier}
                  feedIdentifier={feedIdentifier}
                  customFeedIdentifier={customFeedIdentifier}
                />
              </ErrorBoundary>
            </div>
          )
        ) : (
          <Group
            orientation="horizontal"
            className="min-h-0 flex-1"
            defaultLayout={detailLayout.defaultLayout}
            onLayoutChanged={detailLayout.onLayoutChanged}
            groupRef={detailGroupRef}
          >
            <Panel id="entry-list" defaultSize={selectedEntryIdentifier ? "40%" : "100%"} minSize="25%">
              <div data-panel-zone="entryList" className={classNames(
                "h-full",
                focusedPanel === "entryList" ? "border-t-2 border-t-text-dim" : "border-t-2 border-t-transparent"
              )}>
                <ErrorBoundary>
                  <EntryList
                    feedFilter={feedFilter}
                    folderIdentifier={folderIdentifier}
                    feedIdentifier={feedIdentifier}
                    customFeedIdentifier={customFeedIdentifier}
                  />
                </ErrorBoundary>
              </div>
            </Panel>
            {selectedEntryIdentifier && (
              <>
                <Separator className="w-px bg-border transition-colors hover:bg-text-dim" />
                <Panel id="detail-panel" defaultSize="60%" minSize="30%">
                  <div data-panel-zone="detailPanel" className={classNames(
                    "h-full overflow-hidden",
                    focusedPanel === "detailPanel" ? "border-t-2 border-t-text-dim" : "border-t-2 border-t-transparent"
                  )}>
                    <ErrorBoundary>
                      <EntryDetailPanel
                        entryIdentifier={selectedEntryIdentifier}
                      />
                    </ErrorBoundary>
                  </div>
                </Panel>
              </>
            )}
          </Group>
        )}
      </ErrorBoundary>
    </div>
  )
}
