import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import client from '../api/client'

export default function RegisterSitePage() {
  const navigate = useNavigate()
  const [form, setForm] = useState({
    name: '',
    owner_name: '',
    contact_email: '',
    license_expires_at: '',
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [created, setCreated] = useState(null) // { site_id, secret_key, name }
  const [copied, setCopied] = useState(false)

  function update(k, v) {
    setForm(f => ({ ...f, [k]: v }))
  }

  async function handleSubmit(e) {
    e.preventDefault()
    if (!form.name.trim() || !form.owner_name.trim() || !form.contact_email.trim() || !form.license_expires_at) return
    setError('')
    setLoading(true)
    try {
      const { data } = await client.post('/api/sites/', {
        name: form.name.trim(),
        owner_name: form.owner_name.trim(),
        contact_email: form.contact_email.trim(),
        license_expires_at: new Date(form.license_expires_at).toISOString(),
      })
      setCreated(data)
    } catch (err) {
      setError(err.response?.data?.detail || 'Registration failed')
    } finally {
      setLoading(false)
    }
  }

  async function copyAll() {
    const text = `SITE_ID=${created.site_id}\nSITE_SECRET=${created.secret_key}`
    await navigator.clipboard.writeText(text)
    setCopied(true)
    setTimeout(() => setCopied(false), 2500)
  }

  if (created) {
    return (
      <div className="max-w-lg">
        <div className="bg-emerald-900/20 border border-emerald-700/50 rounded-xl p-6 mb-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-8 h-8 bg-emerald-500/20 rounded-full flex items-center justify-center">
              <svg className="w-4 h-4 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-white font-semibold">Site Registered: {created.name}</h2>
          </div>

          <div className="bg-yellow-900/30 border border-yellow-700/50 rounded-lg px-4 py-3 mb-5 flex items-start gap-2">
            <svg className="w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
            </svg>
            <p className="text-yellow-300 text-sm font-medium">
              Copy these credentials now. The secret key will <strong>never</strong> be shown again.
            </p>
          </div>

          <div className="space-y-3 mb-5">
            <div>
              <label className="text-xs text-gray-500 uppercase tracking-wider block mb-1">Site ID</label>
              <div className="bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 font-mono text-sm text-cyan-300 select-all break-all">
                {created.site_id}
              </div>
            </div>
            <div>
              <label className="text-xs text-gray-500 uppercase tracking-wider block mb-1">Secret Key</label>
              <div className="bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 font-mono text-sm text-cyan-300 select-all break-all">
                {created.secret_key}
              </div>
            </div>
          </div>

          <div className="text-xs text-gray-500 mb-5 bg-gray-900/60 border border-gray-700 rounded-lg px-3 py-2">
            <p className="font-medium text-gray-400 mb-1">Set these in the local backend <code>.env</code>:</p>
            <pre className="text-gray-300 font-mono whitespace-pre-wrap">SITE_ID={created.site_id}{'\n'}SITE_SECRET={created.secret_key}</pre>
          </div>

          <div className="flex gap-3">
            <button
              onClick={copyAll}
              className="flex items-center gap-2 bg-cyan-700 hover:bg-cyan-600 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
              {copied ? 'Copied!' : 'Copy .env vars'}
            </button>
            <button
              onClick={() => navigate(`/sites/${created.site_id}`)}
              className="text-sm text-gray-400 hover:text-white px-4 py-2 rounded-lg transition-colors"
            >
              View Site →
            </button>
          </div>
        </div>

        <button
          onClick={() => navigate('/sites')}
          className="text-sm text-gray-500 hover:text-gray-300 transition-colors"
        >
          ← Back to all sites
        </button>
      </div>
    )
  }

  return (
    <div className="max-w-md">
      <button
        onClick={() => navigate('/sites')}
        className="flex items-center gap-1.5 text-gray-500 hover:text-gray-300 text-sm mb-6 transition-colors"
      >
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        All Sites
      </button>

      <h1 className="text-xl font-bold text-white mb-6">Register New Site</h1>

      <form onSubmit={handleSubmit} className="bg-gray-900 border border-gray-700 rounded-xl p-5 space-y-4">
        <div>
          <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wider">Restaurant Name</label>
          <input
            type="text"
            value={form.name}
            onChange={e => update('name', e.target.value)}
            className="w-full bg-gray-800 border border-gray-600 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-1 focus:ring-cyan-500 focus:border-cyan-500 placeholder-gray-600"
            placeholder="e.g. Taverna Kostas"
            required
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wider">Owner Name</label>
          <input
            type="text"
            value={form.owner_name}
            onChange={e => update('owner_name', e.target.value)}
            className="w-full bg-gray-800 border border-gray-600 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-1 focus:ring-cyan-500 focus:border-cyan-500 placeholder-gray-600"
            placeholder="e.g. Kostas Papadopoulos"
            required
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wider">Contact Email</label>
          <input
            type="email"
            value={form.contact_email}
            onChange={e => update('contact_email', e.target.value)}
            className="w-full bg-gray-800 border border-gray-600 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-1 focus:ring-cyan-500 focus:border-cyan-500 placeholder-gray-600"
            placeholder="kostas@example.com"
            required
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wider">License Expiry</label>
          <input
            type="date"
            value={form.license_expires_at}
            onChange={e => update('license_expires_at', e.target.value)}
            className="w-full bg-gray-800 border border-gray-600 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-1 focus:ring-cyan-500 focus:border-cyan-500"
            required
          />
        </div>

        {error && (
          <p className="text-red-400 text-sm bg-red-900/20 border border-red-800/50 rounded-lg px-3 py-2">{error}</p>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-cyan-600 hover:bg-cyan-500 disabled:opacity-40 disabled:cursor-not-allowed text-white font-semibold py-2.5 rounded-lg text-sm transition-colors"
        >
          {loading ? 'Registering…' : 'Register Site'}
        </button>
      </form>
    </div>
  )
}
