"use client"

import { useState } from "react"
import { useCustomFeeds } from "@/lib/queries/use-custom-feeds"
import {
  useCreateCustomFeed,
  useUpdateCustomFeed,
  useDeleteCustomFeed,
} from "@/lib/queries/use-custom-feed-mutations"
import { useSubscriptions } from "@/lib/queries/use-subscriptions"
import { useUserProfile } from "@/lib/queries/use-user-profile"
import { TIER_LIMITS } from "@asa-news/shared"

export function CustomFeedsSettings() {
  const { data: customFeeds, isLoading } = useCustomFeeds()
  const { data: subscriptionsData } = useSubscriptions()
  const { data: userProfile } = useUserProfile()
  const createCustomFeed = useCreateCustomFeed()

  const [newName, setNewName] = useState("")
  const [newKeywords, setNewKeywords] = useState("")
  const [newMatchMode, setNewMatchMode] = useState<"and" | "or">("or")
  const [newSourceFolderId, setNewSourceFolderId] = useState<string>("")

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

  function handleCreate(event: React.FormEvent) {
    event.preventDefault()
    const trimmedName = newName.trim()
    const trimmedKeywords = newKeywords.trim()

    if (!trimmedName || !trimmedKeywords) return

    createCustomFeed.mutate({
      name: trimmedName,
      query: trimmedKeywords,
      matchMode: newMatchMode,
      sourceFolderIdentifier: newSourceFolderId || null,
    })

    setNewName("")
    setNewKeywords("")
    setNewMatchMode("or")
    setNewSourceFolderId("")
  }

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

  const feedsList = customFeeds ?? []

  return (
    <div>
      <div className="border-b border-border px-4 py-3">
        <p className="mb-2 text-text-dim">
          {feedsList.length} / {maximumCustomFeeds} custom feeds used
        </p>
        <form onSubmit={handleCreate} className="space-y-2">
          <input
            type="text"
            value={newName}
            onChange={(event) => setNewName(event.target.value)}
            placeholder="feed name"
            className="w-full border border-border bg-background-primary px-3 py-2 text-text-primary outline-none placeholder:text-text-dim focus:border-text-dim"
          />
          <input
            type="text"
            value={newKeywords}
            onChange={(event) => setNewKeywords(event.target.value)}
            placeholder="keywords (space-separated)"
            className="w-full border border-border bg-background-primary px-3 py-2 text-text-primary outline-none placeholder:text-text-dim focus:border-text-dim"
          />
          <div className="flex gap-2">
            <select
              value={newMatchMode}
              onChange={(event) =>
                setNewMatchMode(event.target.value as "and" | "or")
              }
              className="border border-border bg-background-primary px-2 py-2 text-text-secondary outline-none"
            >
              <option value="or">match any keyword</option>
              <option value="and">match all keywords</option>
            </select>
            <select
              value={newSourceFolderId}
              onChange={(event) => setNewSourceFolderId(event.target.value)}
              className="border border-border bg-background-primary px-2 py-2 text-text-secondary outline-none"
            >
              <option value="">all feeds</option>
              {folders.map((folder) => (
                <option key={folder.folderIdentifier} value={folder.folderIdentifier}>
                  {folder.name}
                </option>
              ))}
            </select>
            <button
              type="submit"
              disabled={
                createCustomFeed.isPending ||
                !newName.trim() ||
                !newKeywords.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>
          </div>
        </form>
      </div>
      {feedsList.length === 0 ? (
        <p className="px-4 py-6 text-text-dim">no custom feeds yet</p>
      ) : (
        feedsList.map((customFeed) => (
          <CustomFeedRow
            key={customFeed.identifier}
            customFeed={customFeed}
            folders={folders}
          />
        ))
      )}
    </div>
  )
}

function CustomFeedRow({
  customFeed,
  folders,
}: {
  customFeed: {
    identifier: string
    name: string
    query: string
    matchMode: "and" | "or"
    sourceFolderIdentifier: string | null
    iconUrl: string | null
  }
  folders: { folderIdentifier: string; name: string }[]
}) {
  const updateCustomFeed = useUpdateCustomFeed()
  const deleteCustomFeed = useDeleteCustomFeed()
  const [isEditing, setIsEditing] = useState(false)
  const [editedName, setEditedName] = useState(customFeed.name)
  const [editedKeywords, setEditedKeywords] = useState(customFeed.query)
  const [editedMatchMode, setEditedMatchMode] = useState(customFeed.matchMode)
  const [editedSourceFolderId, setEditedSourceFolderId] = useState(
    customFeed.sourceFolderIdentifier ?? ""
  )
  const [editedIconUrl, setEditedIconUrl] = useState(
    customFeed.iconUrl ?? ""
  )
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)

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

    if (!trimmedName || !trimmedKeywords) return

    updateCustomFeed.mutate({
      customFeedIdentifier: customFeed.identifier,
      name: trimmedName,
      query: trimmedKeywords,
      matchMode: editedMatchMode,
      sourceFolderIdentifier: editedSourceFolderId || null,
      iconUrl: editedIconUrl.trim() || null,
    })
    setIsEditing(false)
  }

  const sourceFolderName = customFeed.sourceFolderIdentifier
    ? folders.find(
        (folder) =>
          folder.folderIdentifier === customFeed.sourceFolderIdentifier
      )?.name ?? "unknown folder"
    : "all feeds"

  return (
    <div className="border-b border-border px-4 py-3 last:border-b-0">
      {isEditing ? (
        <div className="space-y-2">
          <input
            type="text"
            value={editedName}
            onChange={(event) => setEditedName(event.target.value)}
            className="w-full border border-border bg-background-primary px-2 py-1 text-text-primary outline-none focus:border-text-dim"
            autoFocus
          />
          <input
            type="text"
            value={editedKeywords}
            onChange={(event) => setEditedKeywords(event.target.value)}
            className="w-full border border-border bg-background-primary px-2 py-1 text-text-primary outline-none focus:border-text-dim"
          />
          <div className="flex gap-2">
            <select
              value={editedMatchMode}
              onChange={(event) =>
                setEditedMatchMode(event.target.value as "and" | "or")
              }
              className="border border-border bg-background-primary px-2 py-1 text-text-secondary outline-none"
            >
              <option value="or">match any</option>
              <option value="and">match all</option>
            </select>
            <select
              value={editedSourceFolderId}
              onChange={(event) => setEditedSourceFolderId(event.target.value)}
              className="border border-border bg-background-primary px-2 py-1 text-text-secondary outline-none"
            >
              <option value="">all feeds</option>
              {folders.map((folder) => (
                <option
                  key={folder.folderIdentifier}
                  value={folder.folderIdentifier}
                >
                  {folder.name}
                </option>
              ))}
            </select>
          </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={() => setIsEditing(false)}
              className="px-2 py-1 text-text-secondary transition-colors hover:text-text-primary"
            >
              cancel
            </button>
          </div>
        </div>
      ) : (
        <div>
          <div className="flex items-center justify-between">
            <span className="text-text-primary">{customFeed.name}</span>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setIsEditing(true)}
                className="px-2 py-1 text-text-dim transition-colors hover:text-text-secondary"
              >
                edit
              </button>
              {showDeleteConfirm ? (
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => {
                      deleteCustomFeed.mutate({
                        customFeedIdentifier: customFeed.identifier,
                      })
                      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>
          </div>
          <p className="text-text-dim">
            keywords: {customFeed.query} ({customFeed.matchMode === "and" ? "all" : "any"})
          </p>
          <p className="text-text-dim">source: {sourceFolderName}</p>
        </div>
      )}
    </div>
  )
}
