import { Trash2, Download, Search } from '../../../lib/icons'
import { useNavigate } from 'react-router-dom'
import { Section, Row, DangerButton } from '../_ui'
import { useSavedSearches } from '../../../stores/saved-searches-store'
import { useSmartShelves } from '../../../stores/smart-shelves-store'
import { useLetterboxdLists } from '../../../stores/letterboxd-lists-store'
import { useDiary } from '../../../stores/diary-store'
import { usePersonalData } from '../../../stores/personal-data-store'
import { exportDiary, type ExportFormat } from '../../../lib/diary-export'
import { toast } from '../../../stores/toast-store'

export function PersonalSettingsSection() {
  const navigate = useNavigate()
  const personalEntries = usePersonalData(s => s.entries)
  const personalCount = Object.keys(personalEntries).length
  const diary = useDiary(s => s.entries)
  const savedSearches = useSavedSearches(s => s.searches)
  const smartShelves = useSmartShelves(s => s.shelves)
  const letterboxdLists = useLetterboxdLists(s => s.lists)

  function clearStore(name: string, run: () => void) {
    if (!confirm(`Permanently delete all ${name}? This can't be undone.`)) return
    run()
  }

  function clearLocalStoragePrefixes(prefixes: string[]) {
    try {
      const keys: string[] = []
      for (let i = 0; i < localStorage.length; i++) {
        const k = localStorage.key(i)
        if (k && prefixes.some(p => k.startsWith(p))) keys.push(k)
      }
      for (const k of keys) localStorage.removeItem(k)
    } catch { /* noop */ }
  }

  return (
    <Section id="personal" title="Personal data" description="Local-only data this device keeps about your watching - nothing here syncs to your Jellyfin server">
      <Row label="Personal ratings + notes + rewatches" hint={`${personalCount} ${personalCount === 1 ? 'item' : 'items'} with personal data`}>
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('personal ratings, notes, and rewatch counters', () => {
              const ids = Object.keys(usePersonalData.getState().entries)
              for (const id of ids) usePersonalData.getState().clear(id)
            })
          }
        />
      </Row>
      <Row label="Diary entries" hint={`${diary.length} ${diary.length === 1 ? 'entry' : 'entries'} logged`}>
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('diary entries', () => {
              const all = useDiary.getState().entries.map(e => e.id)
              for (const id of all) useDiary.getState().remove(id)
            })
          }
        />
      </Row>
      <Row label="Export diary" hint="Download your diary as Markdown, JSON, or a Letterboxd-import CSV">
        <ExportButtons disabled={diary.length === 0} />
      </Row>
      <Row label="Saved searches" hint={`${savedSearches.length} ${savedSearches.length === 1 ? 'search' : 'searches'}`}>
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('saved library searches', () => {
              const all = useSavedSearches.getState().searches.map(s => s.id)
              for (const id of all) useSavedSearches.getState().remove(id)
            })
          }
        />
      </Row>
      <Row label="Smart shelves" hint={`${smartShelves.length} ${smartShelves.length === 1 ? 'shelf' : 'shelves'}`}>
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('smart shelves', () => {
              const all = useSmartShelves.getState().shelves.map(s => s.id)
              for (const id of all) useSmartShelves.getState().remove(id)
            })
          }
        />
      </Row>
      <Row label="Imported Letterboxd lists" hint={`${letterboxdLists.length} ${letterboxdLists.length === 1 ? 'list' : 'lists'}`}>
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('imported Letterboxd lists', () => {
              const all = useLetterboxdLists.getState().lists.map(l => l.url)
              for (const url of all) useLetterboxdLists.getState().remove(url)
            })
          }
        />
      </Row>
      <Row label="Duplicate finder" hint="Scan your library for duplicate movies and series">
        <button
          onClick={() => navigate('/duplicates')}
          className="inline-flex items-center gap-1.5 h-9 px-3 rounded-md text-[12px] font-medium bg-elevated/60 text-text-2 border border-border hover:border-border-hover hover:text-text-1 transition-all duration-150 focus-ring"
        >
          <Search size={13} stroke={2} />
          Open scanner
        </button>
      </Row>
      <Row label="Per-show / per-row preferences" hint="Clears layout choices, episode-order picks, mood pick, skip counters, and the time-saved tally">
        <DangerButton
          icon={Trash2}
          label="Clear"
          onConfirm={() =>
            clearStore('saved layout, ordering, and tracking preferences', () => {
              clearLocalStoragePrefixes([
                'episodeOrder:',
                'lib_layout:',
                'row_layout:',
                'jf_skip_count_',
                'jf_skip_dismissed_',
                'jf_time_saved_',
              ])
              try {
                localStorage.removeItem('home_mood')
                localStorage.removeItem('jf_sidebar_pinned')
              } catch { /* noop */ }
            })
          }
        />
      </Row>
    </Section>
  )
}

function ExportButtons({ disabled }: { disabled: boolean }) {
  function run(format: ExportFormat, label: string) {
    if (disabled) return
    try {
      exportDiary(useDiary.getState().entries, format)
      toast(`Exported diary as ${label}`, 'success')
    } catch {
      toast('Export failed', 'error')
    }
  }
  const formats: { format: ExportFormat; label: string; short: string }[] = [
    { format: 'markdown', label: 'Markdown', short: 'MD' },
    { format: 'json', label: 'JSON', short: 'JSON' },
    { format: 'csv', label: 'Letterboxd CSV', short: 'CSV' },
  ]
  return (
    <div className="flex items-center gap-1.5">
      {formats.map(f => (
        <button
          key={f.format}
          onClick={() => run(f.format, f.label)}
          disabled={disabled}
          title={`Export as ${f.label}`}
          className="inline-flex items-center gap-1.5 h-9 px-3 rounded-md text-[12px] font-medium bg-elevated/60 text-text-2 border border-border hover:border-border-hover hover:text-text-1 transition-all duration-150 focus-ring disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <Download size={13} stroke={2} />
          {f.short}
        </button>
      ))}
    </div>
  )
}
