"use client"

import { useState } from "react"
import { useSubscriptions } from "@/lib/queries/use-subscriptions"
import {
  useCreateFolder,
  useRenameFolder,
  useDeleteFolder,
} from "@/lib/queries/use-folder-mutations"
import { useUserProfile } from "@/lib/queries/use-user-profile"
import { TIER_LIMITS } from "@asa-news/shared"

export function FoldersSettings() {
  const [newFolderName, setNewFolderName] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const { data: subscriptionsData, isLoading } = useSubscriptions()
  const { data: userProfile } = useUserProfile()
  const createFolder = useCreateFolder()
  const renameFolder = useRenameFolder()
  const deleteFolder = useDeleteFolder()

  const folders = subscriptionsData?.folders ?? []
  const subscriptions = subscriptionsData?.subscriptions ?? []
  const tier = userProfile?.tier ?? "free"
  const tierLimits = TIER_LIMITS[tier]

  function feedCountForFolder(folderIdentifier: string): number {
    return subscriptions.filter(
      (subscription) => subscription.folderIdentifier === folderIdentifier
    ).length
  }

  function handleCreateFolder(event: React.FormEvent) {
    event.preventDefault()
    const trimmedName = newFolderName.trim()

    if (!trimmedName) return

    createFolder.mutate({ name: trimmedName })
    setNewFolderName("")
  }

  if (isLoading) {
    return <p className="px-4 py-6 text-text-dim">loading folders ...</p>
  }

  const normalizedQuery = searchQuery.toLowerCase().trim()
  const filteredFolders = normalizedQuery
    ? folders.filter((folder) => folder.name.toLowerCase().includes(normalizedQuery))
    : folders

  return (
    <div>
      <div className="border-b border-border px-4 py-3">
        <p className="mb-2 text-text-dim">
          {folders.length} / {tierLimits.maximumFolders} folders used
        </p>
        <form onSubmit={handleCreateFolder} className="mb-2 flex gap-2">
          <input
            type="text"
            value={newFolderName}
            onChange={(event) => setNewFolderName(event.target.value)}
            placeholder="new folder name"
            className="min-w-0 flex-1 border border-border bg-background-primary px-3 py-2 text-text-primary outline-none placeholder:text-text-dim focus:border-text-dim"
          />
          <button
            type="submit"
            disabled={createFolder.isPending || !newFolderName.trim()}
            className="border border-border bg-background-tertiary px-4 py-2 text-text-primary transition-colors hover:bg-border disabled:opacity-50"
          >
            create
          </button>
        </form>
        {folders.length > 5 && (
          <input
            type="text"
            value={searchQuery}
            onChange={(event) => setSearchQuery(event.target.value)}
            placeholder="search folders..."
            className="w-full border border-border bg-background-primary px-3 py-1.5 text-text-primary outline-none placeholder:text-text-dim focus:border-text-dim"
          />
        )}
      </div>
      {filteredFolders.length === 0 ? (
        <p className="px-4 py-6 text-text-dim">
          {folders.length === 0 ? "no folders yet" : "no folders match your search"}
        </p>
      ) : (
        <div>
          {filteredFolders.map((folder) => (
            <FolderRow
              key={folder.folderIdentifier}
              folderIdentifier={folder.folderIdentifier}
              name={folder.name}
              iconUrl={folder.iconUrl}
              feedCount={feedCountForFolder(folder.folderIdentifier)}
              onSave={(name, iconUrl) =>
                renameFolder.mutate({
                  folderIdentifier: folder.folderIdentifier,
                  name,
                  iconUrl,
                })
              }
              onDelete={() =>
                deleteFolder.mutate({
                  folderIdentifier: folder.folderIdentifier,
                })
              }
            />
          ))}
        </div>
      )}
    </div>
  )
}

function FolderRow(properties: {
  folderIdentifier: string
  name: string
  iconUrl: string | null
  feedCount: number
  onSave: (name: string, iconUrl: string | null) => void
  onDelete: () => void
}) {
  const { name, iconUrl, feedCount, onSave, onDelete } = properties
  const [isEditing, setIsEditing] = useState(false)
  const [editedName, setEditedName] = useState(name)
  const [editedIconUrl, setEditedIconUrl] = useState(iconUrl ?? "")
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)

  function handleSave() {
    const trimmedName = editedName.trim()

    if (trimmedName) {
      onSave(trimmedName, editedIconUrl.trim() || null)
    }

    setIsEditing(false)
  }

  return (
    <div className="flex items-center justify-between border-b border-border px-4 py-3 last:border-b-0">
      <div className="min-w-0 flex-1">
        {isEditing ? (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={editedName}
                onChange={(event) => setEditedName(event.target.value)}
                className="min-w-0 flex-1 border border-border bg-background-primary px-2 py-1 text-text-primary outline-none focus:border-text-dim"
                onKeyDown={(event) => {
                  if (event.key === "Enter") handleSave()
                  if (event.key === "Escape") setIsEditing(false)
                }}
                autoFocus
              />
            </div>
            <input
              type="text"
              value={editedIconUrl}
              onChange={(event) => setEditedIconUrl(event.target.value)}
              placeholder="icon url (optional)"
              className="w-full border border-border bg-background-primary px-2 py-1 text-text-primary outline-none placeholder:text-text-dim focus:border-text-dim"
            />
            <div className="flex gap-2">
              <button
                onClick={handleSave}
                className="px-2 py-1 text-text-secondary transition-colors hover:text-text-primary"
              >
                save
              </button>
              <button
                onClick={() => {
                  setEditedName(name)
                  setEditedIconUrl(iconUrl ?? "")
                  setIsEditing(false)
                }}
                className="px-2 py-1 text-text-secondary transition-colors hover:text-text-primary"
              >
                cancel
              </button>
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-2">
            {iconUrl && (
              <img src={iconUrl} alt="" width={16} height={16} className="shrink-0" />
            )}
            <span className="text-text-primary">{name}</span>
            <span className="text-text-dim">
              ({feedCount} feed{feedCount !== 1 && "s"})
            </span>
            <button
              onClick={() => setIsEditing(true)}
              className="px-2 py-1 text-text-dim transition-colors hover:text-text-secondary"
            >
              edit
            </button>
          </div>
        )}
      </div>
      {showDeleteConfirm ? (
        <div className="flex items-center gap-1">
          <span className="text-text-dim">
            {feedCount > 0 ? "has feeds, delete?" : "delete?"}
          </span>
          <button
            onClick={() => {
              onDelete()
              setShowDeleteConfirm(false)
            }}
            className="px-2 py-1 text-status-error transition-colors hover:text-text-primary"
          >
            yes
          </button>
          <button
            onClick={() => setShowDeleteConfirm(false)}
            className="px-2 py-1 text-text-secondary transition-colors hover:text-text-primary"
          >
            no
          </button>
        </div>
      ) : (
        <button
          onClick={() => setShowDeleteConfirm(true)}
          className="px-2 py-1 text-text-secondary transition-colors hover:text-status-error"
        >
          delete
        </button>
      )}
    </div>
  )
}
