'use client'

import { useState } from 'react'
import { api, ApiError } from '@/lib/api'

export default function PrescriptionPage() {
  const [images, setImages] = useState<string[]>([])
  const [patient, setPatient] = useState('')
  const [phone, setPhone] = useState('')
  const [notes, setNotes] = useState('')
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const onFiles = (files: FileList | null) => {
    if (!files) return
    Array.from(files).slice(0, 5 - images.length).forEach((f) => {
      const reader = new FileReader()
      reader.onload = () => setImages((prev) => (prev.length < 5 ? [...prev, reader.result as string] : prev))
      reader.readAsDataURL(f)
    })
  }

  const submit = async () => {
    if (images.length === 0) { setError('Please add at least one prescription image.'); return }
    setBusy(true); setError(null)
    try {
      const r = await api.post<{ message?: string }>('/prescriptions', { images, patient_name: patient || undefined, contact_phone: phone || undefined, notes: notes || undefined })
      setDone(r.message || 'Prescription received. Our pharmacist will review it shortly.')
      setImages([]); setPatient(''); setPhone(''); setNotes('')
    } catch (e) {
      setError((e as ApiError).message || 'Upload failed. Please try again.')
    } finally { setBusy(false) }
  }

  return (
    <div className="container-x py-10">
      <h1 className="text-2xl font-medium text-ink">Upload Prescription</h1>
      <p className="mt-1 text-sm text-muted">Upload your prescription &amp; get your medications delivered.</p>

      <div className="mt-6 grid gap-3 sm:grid-cols-3">
        {[
          { t: 'Upload Prescription', d: 'Add a clear photo of your prescription' },
          { t: 'Pharmacist Review', d: 'Our team verifies and prepares your order' },
          { t: 'Doorstep Delivery', d: 'Receive your medicines at home' },
        ].map((s, i) => (
          <div key={s.t} className="card flex items-start gap-3 p-4">
            <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-brand-strong text-sm font-bold text-white">{i + 1}</span>
            <div>
              <div className="text-sm font-semibold">{s.t}</div>
              <div className="text-[12px] text-muted">{s.d}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 grid gap-6 lg:grid-cols-[1fr_1.2fr]">
        <div className="card p-5">
          <div className="font-semibold">Prescription Guide</div>
          <ul className="mt-3 space-y-2 text-sm text-muted">
            {['Upload a clear image', 'Doctor details visible', 'Date of prescription', 'Patient details', 'Dosage details'].map((g) => (
              <li key={g} className="flex items-center gap-2"><span className="text-accent">✓</span>{g}</li>
            ))}
          </ul>
        </div>

        <div className="card p-5">
          {done ? (
            <div className="grid place-items-center gap-3 py-10 text-center">
              <div className="grid h-12 w-12 place-items-center rounded-full bg-brand-soft text-brand-strong">✓</div>
              <p className="max-w-sm text-sm text-ink">{done}</p>
              <button onClick={() => setDone(null)} className="btn btn-brand">Upload another</button>
            </div>
          ) : (
            <>
              <label className="grid cursor-pointer place-items-center rounded-xl border border-dashed border-hair bg-soft py-10 text-center hover:border-brand">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" className="text-brand"><path d="M12 16V4m0 0 4 4m-4-4L8 8"/><path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/></svg>
                <span className="mt-2 text-sm font-medium text-ink">Click to upload prescription</span>
                <span className="text-[12px] text-muted">JPG / PNG, up to 5 images</span>
                <input type="file" accept="image/*" multiple className="hidden" onChange={(e) => onFiles(e.target.files)} />
              </label>

              {images.length > 0 && (
                <div className="mt-3 flex flex-wrap gap-2">
                  {images.map((src, i) => (
                    <div key={i} className="relative h-20 w-20 overflow-hidden rounded-lg border border-hair">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img src={src} alt="" className="h-full w-full object-cover" />
                      <button onClick={() => setImages((p) => p.filter((_, j) => j !== i))} className="absolute right-0.5 top-0.5 grid h-5 w-5 place-items-center rounded-full bg-black/60 text-[11px] text-white">×</button>
                    </div>
                  ))}
                </div>
              )}

              <div className="mt-4 grid gap-3 sm:grid-cols-2">
                <input value={patient} onChange={(e) => setPatient(e.target.value)} placeholder="Patient name (optional)" className="input" />
                <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Contact phone (optional)" className="input" />
              </div>
              <textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Notes for the pharmacist (optional)" rows={3} className="input mt-3" />

              {error && <p className="mt-3 text-sm text-rose-600">{error}</p>}
              <button onClick={submit} disabled={busy} className="btn btn-primary mt-4 w-full disabled:opacity-60">{busy ? 'Uploading…' : 'Submit Prescription'}</button>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
