import { useState } from 'react'
import { apiFetch } from '../api'
import { useAuth } from '../context/AuthContext'
import { WORKSHOP_SAMPLES_REMOVED_KEY } from '../lib/creations'

const LS_KEYS = [
  'persona_draft_v1',
  'advisor_draft_v1',
  'persona_chat_v1',
  'advisor_chat_v1',
  'creations_v1',
  WORKSHOP_SAMPLES_REMOVED_KEY,
]

type Props = { onClose: () => void }

export function ClearDataModal({ onClose }: Props) {
  const { user } = useAuth()
  const [clearProfile, setClearProfile] = useState(true)
  const [clearLocal, setClearLocal] = useState(true)

  const run = async () => {
    if (clearLocal) {
      for (const k of LS_KEYS) localStorage.removeItem(k)
    }
    if (clearProfile && user) {
      const r = await apiFetch('/api/users/me/clear-data', { method: 'POST' })
      if (!r.ok) {
        alert('Could not clear server data. You may need to sign in again.')
      }
    }
    onClose()
    window.location.reload()
  }

  return (
    <div className="modal-overlay" role="dialog" aria-modal>
      <div className="modal-box">
        <h2>Clear User Data</h2>
        <label style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.75rem' }}>
          <input type="checkbox" checked={clearLocal} onChange={(e) => setClearLocal(e.target.checked)} />
          Clear local drafts (browser storage)
        </label>
        <label style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '1rem' }}>
          <input
            type="checkbox"
            checked={clearProfile && !!user}
            disabled={!user}
            onChange={(e) => setClearProfile(e.target.checked)}
          />
          Clear saved profile on server {user ? '' : '(sign in required)'}
        </label>
        <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end' }}>
          <button type="button" className="btn btn-secondary" onClick={onClose}>
            Cancel
          </button>
          <button type="button" className="btn btn-primary" onClick={run}>
            Clear
          </button>
        </div>
      </div>
    </div>
  )
}
