'use client'

import { useEffect, useState, useCallback } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import Link from 'next/link'
import { ArrowLeft, ChevronLeft, ChevronRight, CheckCircle, Clock, Calendar } from 'lucide-react'
import api from '@/lib/api'
import type { Locale, BookLessonData, SlotAvailability } from '@/types'
import { t as ls } from '@/types'

function getDayLabels(t: (key: string) => string) {
  return [t('bookLessons.daySun'), t('bookLessons.dayMon'), t('bookLessons.dayTue'), t('bookLessons.dayWed'), t('bookLessons.dayThu'), t('bookLessons.dayFri'), t('bookLessons.daySat')]
}

function getMonthLabels(t: (key: string) => string) {
  return [t('bookLessons.monthJan'), t('bookLessons.monthFeb'), t('bookLessons.monthMar'), t('bookLessons.monthApr'), t('bookLessons.monthMay'), t('bookLessons.monthJun'), t('bookLessons.monthJul'), t('bookLessons.monthAug'), t('bookLessons.monthSep'), t('bookLessons.monthOct'), t('bookLessons.monthNov'), t('bookLessons.monthDec')]
}

function formatTime(time: string) {
  const [h, m] = time.split(':')
  const hour = parseInt(h)
  const ampm = hour >= 12 ? 'PM' : 'AM'
  const display = hour > 12 ? hour - 12 : hour === 0 ? 12 : hour
  return `${display}:${m} ${ampm}`
}

function toDateString(date: Date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

export default function BookLessonsPage() {
  const locale = useLocale() as Locale
  const t = useTranslations('services')
  const lp = (path: string) => `/${locale}${path}`

  const [data, setData] = useState<BookLessonData | null>(null)
  const [loading, setLoading] = useState(true)

  // Calendar state
  const today = new Date()
  const [viewMonth, setViewMonth] = useState(today.getMonth())
  const [viewYear, setViewYear] = useState(today.getFullYear())
  const [selectedDate, setSelectedDate] = useState<string | null>(null)
  const [slots, setSlots] = useState<SlotAvailability[]>([])
  const [slotsLoading, setSlotsLoading] = useState(false)
  const [selectedSlot, setSelectedSlot] = useState<string | null>(null)

  // Form state
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [golfId, setGolfId] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    api.getBookLesson()
      .then(setData)
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const availableDays = data?.availableDays ?? []

  const fetchAvailability = useCallback(async (dateStr: string) => {
    setSlotsLoading(true)
    setSlots([])
    setSelectedSlot(null)
    try {
      const result = await api.getBookLessonAvailability(dateStr)
      setSlots(result.slots ?? [])
    } catch {
      setSlots([])
    } finally {
      setSlotsLoading(false)
    }
  }, [])

  const handleDateSelect = (dateStr: string) => {
    setSelectedDate(dateStr)
    setError('')
    fetchAvailability(dateStr)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedDate || !selectedSlot || !firstName || !lastName || !email || !phone) return
    setSubmitting(true)
    setError('')
    try {
      await api.submitLessonBooking({
        date: selectedDate,
        timeSlot: selectedSlot,
        firstName,
        lastName,
        email,
        phone,
        golfId: golfId || undefined,
      })
      setSubmitted(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to submit booking')
    } finally {
      setSubmitting(false)
    }
  }

  // Calendar generation
  const getDaysInMonth = (year: number, month: number) => new Date(year, month + 1, 0).getDate()
  const getFirstDayOfMonth = (year: number, month: number) => new Date(year, month, 1).getDay()

  const prevMonth = () => {
    if (viewMonth === 0) { setViewMonth(11); setViewYear(viewYear - 1) }
    else setViewMonth(viewMonth - 1)
  }
  const nextMonth = () => {
    if (viewMonth === 11) { setViewMonth(0); setViewYear(viewYear + 1) }
    else setViewMonth(viewMonth + 1)
  }

  const isPastDate = (year: number, month: number, day: number) => {
    const d = new Date(year, month, day)
    const t = new Date()
    t.setHours(0, 0, 0, 0)
    return d < t
  }

  const renderCalendar = () => {
    const daysInMonth = getDaysInMonth(viewYear, viewMonth)
    const firstDay = getFirstDayOfMonth(viewYear, viewMonth)
    const dayLabels = getDayLabels(t)
    const monthLabels = getMonthLabels(t)

    const cells: React.ReactNode[] = []

    for (let i = 0; i < firstDay; i++) {
      cells.push(<div key={`empty-${i}`} />)
    }

    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(viewYear, viewMonth, day)
      const dayOfWeek = date.getDay()
      const dateStr = toDateString(date)
      const isAvailable = availableDays.includes(dayOfWeek) && !isPastDate(viewYear, viewMonth, day)
      const isSelected = selectedDate === dateStr
      const isToday = toDateString(today) === dateStr

      cells.push(
        <button
          key={day}
          type="button"
          disabled={!isAvailable}
          onClick={() => handleDateSelect(dateStr)}
          className={`
            aspect-square flex items-center justify-center rounded-lg text-sm font-medium transition-all
            ${isSelected
              ? 'bg-primary-600 text-white shadow-md'
              : isAvailable
                ? 'bg-gray-50 text-secondary-900 hover:bg-primary-50 hover:text-primary-700 border border-gray-100'
                : 'text-gray-300 cursor-not-allowed'
            }
            ${isToday && !isSelected ? 'ring-2 ring-primary-300' : ''}
          `}
        >
          {day}
        </button>
      )
    }

    const canGoPrev = viewYear > today.getFullYear() || (viewYear === today.getFullYear() && viewMonth > today.getMonth())

    return (
      <div>
        <div className="flex items-center justify-between mb-4">
          <button type="button" onClick={prevMonth} disabled={!canGoPrev} className="p-1.5 rounded-lg hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed">
            <ChevronLeft className="h-5 w-5 text-gray-600" />
          </button>
          <h3 className="text-lg font-semibold text-secondary-900">
            {monthLabels[viewMonth]} {viewYear}
          </h3>
          <button type="button" onClick={nextMonth} className="p-1.5 rounded-lg hover:bg-gray-100">
            <ChevronRight className="h-5 w-5 text-gray-600" />
          </button>
        </div>
        <div className="grid grid-cols-7 gap-1 mb-2">
          {dayLabels.map((d) => (
            <div key={d} className="text-center text-xs font-medium text-gray-500 py-1">{d}</div>
          ))}
        </div>
        <div className="grid grid-cols-7 gap-1">
          {cells}
        </div>
      </div>
    )
  }

  if (loading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="w-10 h-10 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin" />
      </div>
    )
  }

  const heroTitle = data ? ls(data.heroTitle, locale) : ''
  const heroSubtitle = data ? ls(data.heroSubtitle, locale) : ''
  const heroDesc = data ? ls(data.heroDescription, locale) : ''
  const heroImage = data?.heroImage
  const heroCtaText = data ? ls(data.heroCtaText, locale) : ''
  const heroCtaLink = data?.heroCtaLink || ''
  const bookingTitle = data ? ls(data.bookingTitle, locale) : ''
  const bookingSubtitle = data ? ls(data.bookingSubtitle, locale) : ''
  const bookingDesc = data ? ls(data.bookingDescription, locale) : ''
  const terms = data?.termsAndConditions ?? []

  return (
    <div>
      {/* Hero */}
      <section
        className="relative min-h-[calc(100dvh-4rem)] lg:min-h-[calc(100dvh-100px)] flex items-end bg-secondary-950 overflow-hidden"
        style={heroImage ? { backgroundImage: `url(${heroImage})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
      >
        {heroImage && <div className="absolute inset-0 bg-secondary-950/60" />}
        <div className="relative z-10 max-w-7xl mx-auto container-padding pb-16 md:pb-24 pt-32 w-full text-white">
          <Link href={lp('/services')} className="inline-flex items-center text-sm font-semibold mb-8 transition-colors text-white/80 hover:text-white">
            <ArrowLeft className="mr-1.5 h-4 w-4" />
            {t('backToServices')}
          </Link>
          <div className="max-w-3xl">
            <span className="section-label !text-white/70">
              {t('bookLessons.label')}
            </span>
            <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 tracking-tight text-white">
              {heroTitle}
            </h1>
            {heroSubtitle && (
              <p className="text-2xl font-semibold mb-4 text-white/70">
                {heroSubtitle}
              </p>
            )}
            {heroDesc && (
              <p className="text-lg leading-relaxed mb-8 text-white/70">
                {heroDesc}
              </p>
            )}
            {heroCtaText && heroCtaLink && (
              <a
                href={heroCtaLink}
                target="_blank"
                rel="noopener noreferrer"
                className="btn btn-primary text-lg"
              >
                {heroCtaText}
              </a>
            )}
          </div>
        </div>
      </section>

      {/* Booking Section */}
      <section className="py-24 md:py-32">
        <div className="max-w-7xl mx-auto container-padding">
          <div className="text-center mb-14">
            <h2 className="text-3xl md:text-4xl font-bold text-secondary-900 mb-3 tracking-tight">{bookingTitle}</h2>
            {bookingSubtitle && <p className="text-lg text-primary-600 font-medium mb-2">{bookingSubtitle}</p>}
            {bookingDesc && <p className="text-secondary-600">{bookingDesc}</p>}
          </div>

          {submitted ? (
            <div className="max-w-lg mx-auto bg-white rounded-sm shadow-sm p-12 text-center">
              <CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-6" />
              <h3 className="text-2xl font-bold text-secondary-900 mb-3">
                {t('bookLessons.bookingConfirmed')}
              </h3>
              <p className="text-secondary-600 mb-6">
                {t('bookLessons.checkEmail')}
              </p>
              <button
                onClick={() => {
                  setSubmitted(false)
                  setSelectedDate(null)
                  setSelectedSlot(null)
                  setFirstName('')
                  setLastName('')
                  setEmail('')
                  setPhone('')
                  setGolfId('')
                }}
                className="text-primary-600 font-medium hover:text-primary-700"
              >
                {t('bookLessons.bookAnother')}
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              {/* Calendar */}
              <div className="bg-white rounded-sm shadow-sm p-6">
                <div className="flex items-center gap-2 mb-6">
                  <Calendar className="h-5 w-5 text-primary-600" />
                  <h3 className="text-lg font-semibold text-secondary-900">
                    {t('bookLessons.selectDate')}
                  </h3>
                </div>
                {renderCalendar()}

                {/* Time slots */}
                {selectedDate && (
                  <div className="mt-6 pt-6 border-t border-gray-200">
                    <div className="flex items-center gap-2 mb-4">
                      <Clock className="h-5 w-5 text-primary-600" />
                      <h3 className="text-lg font-semibold text-secondary-900">
                        {t('bookLessons.selectTime')}
                      </h3>
                    </div>
                    {slotsLoading ? (
                      <div className="flex justify-center py-6">
                        <div className="w-10 h-10 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin" />
                      </div>
                    ) : slots.length === 0 ? (
                      <p className="text-sm text-gray-500 py-4 text-center">
                        {t('bookLessons.noSlots')}
                      </p>
                    ) : (
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        {slots.map((slot) => {
                          const slotKey = `${slot.startTime}-${slot.endTime}`
                          const isSelected = selectedSlot === slotKey
                          return (
                            <button
                              key={slotKey}
                              type="button"
                              disabled={!slot.available}
                              onClick={() => { setSelectedSlot(slotKey); setError('') }}
                              className={`
                                p-4 rounded-sm border-2 text-left transition-all
                                ${isSelected
                                  ? 'border-primary-600 bg-primary-50'
                                  : slot.available
                                    ? 'border-gray-200 bg-white hover:border-primary-300'
                                    : 'border-gray-100 bg-gray-50 opacity-50 cursor-not-allowed'
                                }
                              `}
                            >
                              <p className={`text-sm font-semibold ${isSelected ? 'text-primary-700' : 'text-secondary-900'}`}>
                                {formatTime(slot.startTime)} - {formatTime(slot.endTime)}
                              </p>
                              <p className={`text-xs mt-1 ${slot.available ? 'text-green-600' : 'text-red-500'}`}>
                                {slot.available ? t('bookLessons.available') : t('bookLessons.fullyBooked')}
                              </p>
                            </button>
                          )
                        })}
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Booking Form */}
              <div className="bg-white rounded-sm shadow-sm p-6">
                <h3 className="text-lg font-semibold text-secondary-900 mb-6">
                  {t('bookLessons.yourDetails')}
                </h3>

                {!selectedDate || !selectedSlot ? (
                  <div className="py-12 text-center text-gray-400">
                    <Calendar className="h-12 w-12 mx-auto mb-3 opacity-40" />
                    <p className="text-sm">
                      {t('bookLessons.selectFirst')}
                    </p>
                  </div>
                ) : (
                  <form onSubmit={handleSubmit} className="space-y-4">
                    <div className="bg-primary-50 rounded-lg p-3 mb-2">
                      <p className="text-sm text-primary-700 font-medium">
                        {new Date(selectedDate).toLocaleDateString(t('bookLessons.dateLocale'), {
                          weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
                        })}
                        {' '}&bull;{' '}
                        {selectedSlot.split('-').map(formatTime).join(' - ')}
                      </p>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          {t('bookLessons.firstName')} *
                        </label>
                        <input
                          value={firstName}
                          onChange={(e) => setFirstName(e.target.value)}
                          required
                          className="w-full px-3 py-2.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          {t('bookLessons.lastName')} *
                        </label>
                        <input
                          value={lastName}
                          onChange={(e) => setLastName(e.target.value)}
                          required
                          className="w-full px-3 py-2.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                        />
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        {t('bookLessons.email')} *
                      </label>
                      <input
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                        className="w-full px-3 py-2.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        {t('bookLessons.phone')} *
                      </label>
                      <input
                        type="tel"
                        value={phone}
                        onChange={(e) => setPhone(e.target.value)}
                        required
                        className="w-full px-3 py-2.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Golf ID
                      </label>
                      <input
                        value={golfId}
                        onChange={(e) => setGolfId(e.target.value)}
                        placeholder={t('bookLessons.optional')}
                        className="w-full px-3 py-2.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                      />
                    </div>

                    {error && (
                      <div className="bg-red-50 text-red-700 text-sm rounded-lg p-3">
                        {error}
                      </div>
                    )}

                    <button
                      type="submit"
                      disabled={submitting}
                      className="w-full bg-primary-600 text-white font-semibold py-3 rounded-lg hover:bg-primary-700 transition-colors disabled:opacity-50 text-lg"
                    >
                      {submitting ? t('bookLessons.submitting') : t('bookLessons.confirmBooking')}
                    </button>
                  </form>
                )}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* Terms & Conditions */}
      {terms.length > 0 && (
        <section className="py-16 bg-gray-50">
          <div className="max-w-4xl mx-auto container-padding">
            <h2 className="text-xl font-bold text-secondary-900 mb-6">
              {t('bookLessons.termsTitle')}
            </h2>
            <ol className="space-y-4">
              {terms.map((term, i) => (
                <li key={i} className="flex gap-3">
                  <span className="text-primary-600 font-semibold min-w-[1.5rem] text-right">{i + 1}.</span>
                  <p className="text-secondary-600 leading-relaxed">{ls(term, locale)}</p>
                </li>
              ))}
            </ol>
          </div>
        </section>
      )}
    </div>
  )
}
