'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { Card, Address } from '@/libs/frontend-ui-primitives'

export default function WatchlistPage() {
  const [entries, setEntries] = useState<string[]>([])

  useEffect(() => {
    try {
      const raw = window.localStorage.getItem('explorerWatchlist')
      const parsed = raw ? JSON.parse(raw) : []
      setEntries(Array.isArray(parsed) ? parsed.filter((entry): entry is string => typeof entry === 'string') : [])
    } catch {
      setEntries([])
    }
  }, [])

  const removeEntry = (address: string) => {
    setEntries((current) => {
      const next = current.filter((entry) => entry.toLowerCase() !== address.toLowerCase())
      try {
        window.localStorage.setItem('explorerWatchlist', JSON.stringify(next))
      } catch {}
      return next
    })
  }

  const exportWatchlist = () => {
    try {
      const blob = new Blob([JSON.stringify(entries, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const anchor = document.createElement('a')
      anchor.href = url
      anchor.download = 'explorer-watchlist.json'
      anchor.click()
      URL.revokeObjectURL(url)
    } catch {}
  }

  const importWatchlist = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    file.text().then((text) => {
      try {
        const parsed = JSON.parse(text)
        const next = Array.isArray(parsed)
          ? parsed.filter((entry): entry is string => typeof entry === 'string')
          : []
        setEntries(next)
        window.localStorage.setItem('explorerWatchlist', JSON.stringify(next))
      } catch {}
    }).catch(() => {})

    event.target.value = ''
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Watchlist</h1>

      <Card title="Saved Addresses">
        <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {entries.length === 0 ? 'No saved entries yet.' : `${entries.length} saved ${entries.length === 1 ? 'address' : 'addresses'}.`}
          </p>
          <div className="flex flex-wrap gap-2">
            <label className="cursor-pointer rounded-lg bg-gray-100 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700">
              Import JSON
              <input type="file" accept="application/json" className="hidden" onChange={importWatchlist} />
            </label>
            <button
              type="button"
              onClick={exportWatchlist}
              disabled={entries.length === 0}
              className="rounded-lg bg-primary-600 px-3 py-1.5 text-sm text-white hover:bg-primary-700 disabled:opacity-50"
            >
              Export JSON
            </button>
          </div>
        </div>
        {entries.length === 0 ? (
          <div className="space-y-3 text-sm text-gray-600 dark:text-gray-400">
            <p>Your watchlist is empty. Add an address from its detail page to keep it here.</p>
            <div className="flex flex-wrap gap-3">
              <Link href="/addresses" className="text-primary-600 hover:underline">
                Browse addresses →
              </Link>
              <Link href="/search" className="text-primary-600 hover:underline">
                Search the explorer →
              </Link>
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {entries.map((entry) => (
              <div key={entry} className="flex flex-col gap-2 rounded-lg border border-gray-200 p-3 dark:border-gray-700 md:flex-row md:items-center md:justify-between">
                <Link href={`/addresses/${entry}`} className="text-primary-600 hover:underline">
                  <Address address={entry} />
                </Link>
                <button
                  type="button"
                  onClick={() => removeEntry(entry)}
                  className="rounded-lg bg-gray-100 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700"
                >
                  Remove
                </button>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  )
}
