import { useState } from 'react'
import { readJson, writeJson, storageKeys } from '../lib/storage'
import { usePolls } from '../context/PollContext'

/** Clean poll admin only — no credential capture, no password logs. */
export default function Admin() {
  const { polls, createPoll, closePoll, deletePoll } = usePolls()
  const [unlocked, setUnlocked] = useState(() => Boolean(readJson(storageKeys.ADMIN_KEY, false)))
  const [pin, setPin] = useState('')
  const [error, setError] = useState('')
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [optionsText, setOptionsText] = useState('Nominee A\nNominee B\nNominee C')

  const unlock = (event) => {
    event.preventDefault()
    // Local-only gate for demo. Replace with real auth later.
    if (pin.trim() === 'votetech') {
      writeJson(storageKeys.ADMIN_KEY, true)
      setUnlocked(true)
      setError('')
      return
    }
    setError('Invalid admin PIN')
  }

  const lock = () => {
    localStorage.removeItem(storageKeys.ADMIN_KEY)
    setUnlocked(false)
    setPin('')
  }

  const onCreate = (event) => {
    event.preventDefault()
    const options = optionsText
      .split('\n')
      .map((line) => line.trim())
      .filter(Boolean)
    if (!title.trim() || options.length < 2) {
      setError('Add a title and at least two nominees.')
      return
    }
    createPoll({ title: title.trim(), description: description.trim(), options })
    setTitle('')
    setDescription('')
    setOptionsText('Nominee A\nNominee B\nNominee C')
    setError('')
  }

  if (!unlocked) {
    return (
      <div className="mx-auto flex min-h-[50vh] max-w-md flex-col justify-center px-4 py-16">
        <form onSubmit={unlock} className="rounded-3xl border border-brand-200 bg-white p-8 shadow-sm">
          <h1 className="brand-heading text-2xl font-bold">Poll Admin</h1>
          <p className="mt-2 text-sm text-brand-700/75">
            Manage polls and nominees only. This panel does not store or view user credentials.
          </p>
          <input
            type="password"
            value={pin}
            onChange={(e) => setPin(e.target.value)}
            placeholder="Admin PIN"
            className="mt-6 w-full rounded-xl border border-brand-300 px-4 py-3 text-sm outline-none focus:border-brand-500"
          />
          <button type="submit" className="mt-4 w-full rounded-full bg-brand-700 py-3 text-sm font-semibold text-white">
            Unlock
          </button>
          {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
          <p className="mt-4 text-xs text-brand-700/60">Demo PIN: votetech</p>
        </form>
      </div>
    )
  }

  return (
    <div className="mx-auto max-w-4xl px-4 py-10 sm:px-6 lg:px-8">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="brand-heading text-3xl font-bold">Poll Admin</h1>
          <p className="mt-1 text-sm text-brand-700/75">Create, close, and remove polls. No credential capture.</p>
        </div>
        <button type="button" onClick={lock} className="rounded-full border border-brand-300 px-4 py-2 text-sm font-semibold">
          Lock
        </button>
      </div>

      <form onSubmit={onCreate} className="mt-8 space-y-4 rounded-3xl border border-brand-200 bg-white p-6 shadow-sm">
        <h2 className="brand-heading text-xl font-bold">Create poll</h2>
        <input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Poll title"
          className="w-full rounded-xl border border-brand-300 px-4 py-3 text-sm outline-none focus:border-brand-500"
        />
        <input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Short description"
          className="w-full rounded-xl border border-brand-300 px-4 py-3 text-sm outline-none focus:border-brand-500"
        />
        <textarea
          value={optionsText}
          onChange={(e) => setOptionsText(e.target.value)}
          rows={5}
          placeholder="One nominee per line"
          className="w-full rounded-xl border border-brand-300 px-4 py-3 text-sm outline-none focus:border-brand-500"
        />
        <button type="submit" className="rounded-full bg-brand-700 px-5 py-3 text-sm font-semibold text-white">
          Create poll
        </button>
        {error && <p className="text-sm text-red-600">{error}</p>}
      </form>

      <div className="mt-8 space-y-4">
        {polls.map((poll) => (
          <div key={poll.id} className="rounded-3xl border border-brand-200 bg-white p-5 shadow-sm">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p className="font-semibold">{poll.title}</p>
                <p className="text-xs text-brand-700/70">
                  {poll.status} · {poll.options.length} nominees ·{' '}
                  {poll.options.reduce((sum, o) => sum + o.votes, 0)} votes
                </p>
              </div>
              <div className="flex gap-2">
                {poll.status === 'open' && (
                  <button
                    type="button"
                    onClick={() => closePoll(poll.id)}
                    className="rounded-full border border-brand-300 px-4 py-2 text-sm font-semibold"
                  >
                    Close
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => {
                    if (window.confirm('Delete this poll?')) deletePoll(poll.id)
                  }}
                  className="rounded-full border border-red-500 px-4 py-2 text-sm font-semibold text-red-600"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
