'use client'

import { Suspense, useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { Star } from 'lucide-react'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000/api/v1'

interface ReviewInfo {
  reservationId: string
  companyName: string
  companyLogoUrl: string | null
  vehicle: string
  vehiclePhoto: string | null
}

function StarRating({ value, onChange, label }: { value: number; onChange: (v: number) => void; label: string }) {
  const [hovered, setHovered] = useState(0)
  return (
    <div>
      <p className="mb-1.5 text-sm font-medium text-stone-700 dark:text-stone-300">{label}</p>
      <div className="flex gap-1">
        {[1, 2, 3, 4, 5].map((n) => (
          <button
            key={n}
            type="button"
            onClick={() => onChange(n)}
            onMouseEnter={() => setHovered(n)}
            onMouseLeave={() => setHovered(0)}
            className="p-0.5 transition-transform hover:scale-110"
            aria-label={`${n} star${n > 1 ? 's' : ''}`}
          >
            <Star
              className={`h-8 w-8 transition-colors ${
                n <= (hovered || value)
                  ? 'fill-orange-400 text-orange-400'
                  : 'fill-stone-200 text-stone-200 dark:fill-stone-700 dark:text-stone-700'
              }`}
            />
          </button>
        ))}
      </div>
    </div>
  )
}

function ReviewPageContent() {
  const params = useSearchParams()
  const token = params.get('token') ?? ''

  const [info, setInfo] = useState<ReviewInfo | null>(null)
  const [loadState, setLoadState] = useState<'loading' | 'ready' | 'already_reviewed' | 'invalid'>('loading')

  const [overall, setOverall] = useState(0)
  const [vehicle, setVehicle] = useState(0)
  const [service, setService] = useState(0)
  const [comment, setComment] = useState('')
  const [submitState, setSubmitState] = useState<'idle' | 'submitting' | 'done' | 'error'>('idle')
  const [errorMsg, setErrorMsg] = useState('')

  useEffect(() => {
    if (!token) { setLoadState('invalid'); return }
    fetch(`${API_BASE}/marketplace/review/${token}`)
      .then(async (r) => {
        if (r.status === 409) { setLoadState('already_reviewed'); return }
        if (!r.ok) { setLoadState('invalid'); return }
        const json = await r.json()
        setInfo(json.data)
        setLoadState('ready')
      })
      .catch(() => setLoadState('invalid'))
  }, [token])

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (overall === 0) { setErrorMsg('Please select an overall rating.'); return }
    setSubmitState('submitting')
    setErrorMsg('')
    try {
      const res = await fetch(`${API_BASE}/marketplace/review/${token}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          overallRating: overall,
          vehicleRating: vehicle || undefined,
          serviceRating: service || undefined,
          comment: comment.trim() || undefined,
        }),
      })
      if (res.status === 409) { setLoadState('already_reviewed'); return }
      if (!res.ok) {
        const json = await res.json()
        throw new Error(json.message ?? 'Something went wrong.')
      }
      setSubmitState('done')
    } catch (err: any) {
      setSubmitState('error')
      setErrorMsg(err.message ?? 'Something went wrong. Please try again.')
    }
  }

  if (loadState === 'loading') {
    return (
      <main className="site-page flex min-h-screen items-center justify-center p-6">
        <p className="text-sm text-stone-500 dark:text-stone-400">Loading…</p>
      </main>
    )
  }

  if (loadState === 'invalid') {
    return (
      <main className="site-page flex min-h-screen items-center justify-center p-6">
        <div className="card w-full max-w-md space-y-3 p-8 text-center">
          <p className="text-2xl font-black text-stone-900 dark:text-stone-100">Link not found</p>
          <p className="text-sm text-stone-500 dark:text-stone-400">This review link is invalid or has already been used.</p>
        </div>
      </main>
    )
  }

  if (loadState === 'already_reviewed') {
    return (
      <main className="site-page flex min-h-screen items-center justify-center p-6">
        <div className="card w-full max-w-md space-y-3 p-8 text-center">
          <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/50">
            <svg className="h-7 w-7 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" /></svg>
          </div>
          <p className="text-xl font-bold text-stone-900 dark:text-stone-100">Already reviewed</p>
          <p className="text-sm text-stone-500 dark:text-stone-400">You have already submitted a review for this rental. Thank you!</p>
        </div>
      </main>
    )
  }

  if (submitState === 'done') {
    return (
      <main className="site-page flex min-h-screen items-center justify-center p-6">
        <div className="card w-full max-w-md space-y-4 p-8 text-center">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/50">
            <svg className="h-8 w-8 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" /></svg>
          </div>
          <h1 className="text-2xl font-black text-stone-900 dark:text-stone-100">Thank you!</h1>
          <p className="text-stone-500 dark:text-stone-400">Your review has been submitted and will be visible on {info?.companyName}'s profile.</p>
        </div>
      </main>
    )
  }

  return (
    <main className="site-page flex min-h-screen items-center justify-center p-6">
      <div className="card w-full max-w-lg overflow-hidden">
        {/* Header */}
        <div className="flex items-center gap-4 border-b border-stone-200 dark:border-blue-900 p-6">
          {info?.vehiclePhoto ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={info.vehiclePhoto} alt={info.vehicle} className="h-16 w-24 flex-shrink-0 rounded-xl object-cover" />
          ) : (
            <div className="h-16 w-24 flex-shrink-0 rounded-xl bg-stone-100 dark:bg-blue-900/30" />
          )}
          <div className="min-w-0">
            <p className="truncate text-xs uppercase tracking-widest text-stone-400 dark:text-stone-500">{info?.companyName}</p>
            <h1 className="mt-0.5 truncate text-lg font-bold text-stone-900 dark:text-stone-100">{info?.vehicle}</h1>
            <p className="mt-0.5 text-sm text-stone-500 dark:text-stone-400">How was your experience?</p>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6 p-6">
          <StarRating value={overall} onChange={setOverall} label="Overall experience *" />
          <StarRating value={vehicle} onChange={setVehicle} label="Vehicle condition (optional)" />
          <StarRating value={service} onChange={setService} label="Customer service (optional)" />

          <div>
            <label className="mb-1.5 block text-sm font-medium text-stone-700 dark:text-stone-300">Comments (optional)</label>
            <textarea
              rows={4}
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder="Tell us about your rental experience…"
              className="w-full resize-none rounded-xl border border-stone-200 dark:border-blue-800 bg-white dark:bg-blue-950 px-4 py-3 text-sm text-stone-900 dark:text-stone-100 placeholder:text-stone-400 dark:placeholder:text-stone-500 focus:outline-none focus:ring-2 focus:ring-stone-900 dark:focus:ring-stone-400"
            />
          </div>

          {errorMsg && (
            <p className="rounded-xl bg-rose-50 dark:bg-rose-950/40 px-4 py-3 text-sm text-rose-700 dark:text-rose-400">{errorMsg}</p>
          )}

          <button
            type="submit"
            disabled={submitState === 'submitting'}
            className="w-full rounded-full bg-orange-600 py-3 text-sm font-semibold text-white transition-colors hover:bg-orange-700 disabled:opacity-60 dark:bg-orange-500 dark:text-white dark:hover:bg-orange-400"
          >
            {submitState === 'submitting' ? 'Submitting…' : 'Submit review'}
          </button>
        </form>
      </div>
    </main>
  )
}

export default function ReviewPage() {
  return (
    <Suspense
      fallback={
        <main className="site-page flex min-h-screen items-center justify-center p-6">
          <p className="text-sm text-stone-500 dark:text-stone-400">Loading…</p>
        </main>
      }
    >
      <ReviewPageContent />
    </Suspense>
  )
}
