"use client"

import { useState, useRef } from "react"
import { useSubscriptions } from "@/lib/queries/use-subscriptions"
import { useSubscribeToFeed } from "@/lib/queries/use-subscribe-to-feed"
import { useUserProfile } from "@/lib/queries/use-user-profile"
import { downloadOpml, parseOpml } from "@/lib/opml"
import type { ParsedOpmlGroup } from "@/lib/opml"
import { notify } from "@/lib/notify"

export function ImportExportSettings() {
  const { data: subscriptionsData } = useSubscriptions()
  const { data: userProfile } = useUserProfile()
  const subscribeToFeed = useSubscribeToFeed()
  const [parsedGroups, setParsedGroups] = useState<ParsedOpmlGroup[] | null>(
    null
  )
  const [isImporting, setIsImporting] = useState(false)
  const [isExportingData, setIsExportingData] = useState(false)
  const fileInputReference = useRef<HTMLInputElement>(null)

  const tier = userProfile?.tier ?? "free"

  function handleExport() {
    if (!subscriptionsData) return

    downloadOpml(subscriptionsData.subscriptions, subscriptionsData.folders)
    notify("subscriptions exported")
  }

  function handleFileSelect(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0]

    if (!file) return

    const reader = new FileReader()
    reader.onload = (loadEvent) => {
      const xmlString = loadEvent.target?.result as string

      try {
        const groups = parseOpml(xmlString)
        setParsedGroups(groups)
      } catch {
        notify("failed to parse opml file")
      }
    }
    reader.readAsText(file)

    if (fileInputReference.current) {
      fileInputReference.current.value = ""
    }
  }

  async function handleImport() {
    if (!parsedGroups) return

    setIsImporting(true)
    let importedCount = 0
    let failedCount = 0

    for (const group of parsedGroups) {
      for (const feed of group.feeds) {
        try {
          await new Promise<void>((resolve) => {
            subscribeToFeed.mutate(
              {
                feedUrl: feed.url,
                customTitle: feed.title || null,
              },
              {
                onSuccess: () => {
                  importedCount++
                  resolve()
                },
                onError: () => {
                  failedCount++
                  resolve()
                },
              }
            )
          })
        } catch {
          failedCount++
        }
      }
    }

    setIsImporting(false)
    setParsedGroups(null)

    if (failedCount > 0) {
      notify(`imported ${importedCount} feeds, ${failedCount} failed`)
    } else {
      notify(`imported ${importedCount} feeds`)
    }
  }

  async function handleDataExport() {
    setIsExportingData(true)
    try {
      const response = await fetch("/api/export")
      if (!response.ok) throw new Error("export failed")
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const anchor = document.createElement("a")
      anchor.href = url
      anchor.download = `asa-news-export-${new Date().toISOString().slice(0, 10)}.json`
      anchor.click()
      URL.revokeObjectURL(url)
      notify("data exported")
    } catch {
      notify("failed to export data")
    } finally {
      setIsExportingData(false)
    }
  }

  const totalFeedsInImport =
    parsedGroups?.reduce((sum, group) => sum + group.feeds.length, 0) ?? 0

  return (
    <div className="px-4 py-3">
      <div className="mb-6">
        <h3 className="mb-2 text-text-primary">import</h3>
        <p className="mb-3 text-text-dim">
          import subscriptions from an opml file
        </p>
        {parsedGroups === null ? (
          <div>
            <input
              ref={fileInputReference}
              type="file"
              accept=".opml,.xml"
              onChange={handleFileSelect}
              className="hidden"
            />
            <button
              onClick={() => fileInputReference.current?.click()}
              className="border border-border bg-background-tertiary px-4 py-2 text-text-primary transition-colors hover:bg-border"
            >
              select opml file
            </button>
          </div>
        ) : (
          <div>
            <p className="mb-3 text-text-secondary">
              found {totalFeedsInImport} feed
              {totalFeedsInImport !== 1 && "s"} to import:
            </p>
            <div className="mb-3 max-h-60 overflow-y-auto border border-border">
              {parsedGroups.map((group, groupIndex) => (
                <div key={groupIndex}>
                  {group.folderName && (
                    <div className="bg-background-tertiary px-3 py-1 text-text-secondary">
                      {group.folderName}
                    </div>
                  )}
                  {group.feeds.map((feed, feedIndex) => (
                    <div
                      key={feedIndex}
                      className="border-b border-border px-3 py-2 last:border-b-0"
                    >
                      <p className="truncate text-text-primary">{feed.title}</p>
                      <p className="truncate text-text-dim">{feed.url}</p>
                    </div>
                  ))}
                </div>
              ))}
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setParsedGroups(null)}
                className="border border-border px-4 py-2 text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
              >
                cancel
              </button>
              <button
                onClick={handleImport}
                disabled={isImporting}
                className="border border-border bg-background-tertiary px-4 py-2 text-text-primary transition-colors hover:bg-border disabled:opacity-50"
              >
                {isImporting
                  ? "importing..."
                  : `import ${totalFeedsInImport} feeds`}
              </button>
            </div>
          </div>
        )}
      </div>
      <div className="mb-6">
        <h3 className="mb-2 text-text-primary">export opml</h3>
        <p className="mb-3 text-text-dim">
          download your subscriptions as an opml file
        </p>
        <button
          onClick={handleExport}
          disabled={!subscriptionsData}
          className="border border-border bg-background-tertiary px-4 py-2 text-text-primary transition-colors hover:bg-border disabled:opacity-50"
        >
          export opml
        </button>
      </div>
      <div>
        <h3 className="mb-2 text-text-primary">export data</h3>
        <p className="mb-3 text-text-dim">
          {tier === "pro" || tier === "developer"
            ? "download all your data as json (subscriptions, folders, saved entries)"
            : "download your saved entries as json (upgrade to pro for full export)"}
        </p>
        <button
          onClick={handleDataExport}
          disabled={isExportingData}
          className="border border-border bg-background-tertiary px-4 py-2 text-text-primary transition-colors hover:bg-border disabled:opacity-50"
        >
          {isExportingData ? "exporting..." : "export data"}
        </button>
      </div>
    </div>
  )
}
