import { useMemo } from 'react'
import { format } from 'date-fns'
import clsx from 'clsx'
import {
  guessDateFromPath,
  toDatetimeLocalValue,
} from '../../lib/guessDateFromPath'
import type { PhotoDetails } from './PhotoInfoPanel'

interface TakenAtEditorProps {
  photo: PhotoDetails
  draft: string
  onDraftChange: (v: string) => void
  onCommit: (raw?: string) => void
  darkTheme: boolean
}

/** Editable Date Taken field with a source badge (EXIF / filesystem / manual)
 *  and a folder-guess suggestion row that only shows up when the filepath
 *  implies a different date than what's currently stored. The suggestion
 *  hint is the whole point of this feature — epoch-reset phones and
 *  corrupted EXIF dumps end up clustered in the wrong corner of the
 *  timeline until someone rewrites them from the folder name. */
export function TakenAtEditor({
  photo,
  draft,
  onDraftChange,
  onCommit,
  darkTheme,
}: TakenAtEditorProps) {
  const source = photo.taken_at_source ?? null
  const sourceLabel =
    source === 'exif'
      ? 'EXIF'
      : source === 'filesystem'
        ? 'FILE'
        : source === 'manual'
          ? 'MANUAL'
          : null

  const guess = useMemo(
    () => guessDateFromPath(photo.filepath),
    [photo.filepath]
  )

  // Show the suggestion when:
  //   - there's no stored date at all, OR
  //   - the guess disagrees with the stored date by more than a day.
  // A same-day match is treated as "already correct enough" so we don't
  // nag the user on photos that happen to sit in a dated folder.
  const showSuggestion = useMemo(() => {
    if (!guess) return false
    if (!photo.taken_at) return true
    const current = new Date(photo.taken_at).getTime()
    const suggested = guess.date.getTime()
    return Math.abs(current - suggested) > 24 * 60 * 60 * 1000
  }, [guess, photo.taken_at])

  const inputClass = clsx(
    'flex-1 rounded border px-2 py-1 text-xs focus:outline-none',
    darkTheme
      ? 'border-white/15 bg-black/40 text-white focus:border-primary'
      : 'border-border bg-bg text-text focus:border-primary'
  )

  return (
    <div className="mt-2 text-xs">
      <label className="mb-1 block text-text-muted">Date Taken</label>
      <div className="flex items-center gap-1.5">
        <input
          type="datetime-local"
          value={draft}
          onChange={(e) => onDraftChange(e.target.value)}
          onBlur={() => onCommit()}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.currentTarget.blur()
            } else if (e.key === 'Escape') {
              onDraftChange(
                photo.taken_at
                  ? toDatetimeLocalValue(new Date(photo.taken_at))
                  : ''
              )
              e.currentTarget.blur()
            }
          }}
          className={inputClass}
        />
        {sourceLabel && (
          <span
            className="rounded-sm bg-black/60 px-1.5 py-0.5 text-[9px] font-semibold tracking-wider text-white"
            title={`Source: ${sourceLabel.toLowerCase()}`}
          >
            {sourceLabel}
          </span>
        )}
      </div>
      {showSuggestion && guess && (
        <button
          onClick={() => {
            const next = toDatetimeLocalValue(guess.date)
            onDraftChange(next)
            onCommit(next)
          }}
          className={clsx(
            'mt-1.5 flex w-full items-center justify-between gap-2 rounded border border-dashed px-2 py-1 text-[11px] transition-colors',
            'border-primary/50 text-primary hover:bg-primary/10'
          )}
          title={`Match "${guess.matched}" in path (${guess.source}, ${guess.confidence} confidence)`}
        >
          <span className="truncate">
            Folder suggests {format(guess.date, 'MMM d, yyyy')}
          </span>
          <span className="shrink-0 font-semibold">Apply</span>
        </button>
      )}
    </div>
  )
}
