'use client'

import { useEffect, useState, useCallback } from 'react'
import { ChevronLeft, ChevronRight, Plus, X, Wrench, Ban, CalendarDays } from 'lucide-react'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'

type EventType = 'RESERVATION' | 'MAINTENANCE' | 'BLOCK'

export interface CalendarEvent {
  id: string
  type: EventType
  startDate: string
  endDate: string
  status: string | null
  label: string
}

interface Props {
  vehicleId: string
}

const EVENT_STYLES: Record<EventType, { bg: string; text: string; border: string; dot: string }> = {
  RESERVATION: { bg: 'bg-blue-100',   text: 'text-blue-800',   border: 'border-blue-300',   dot: 'bg-blue-500'   },
  MAINTENANCE: { bg: 'bg-orange-100',  text: 'text-orange-800',  border: 'border-orange-300',  dot: 'bg-orange-500'  },
  BLOCK:       { bg: 'bg-red-100',    text: 'text-red-800',    border: 'border-red-300',    dot: 'bg-red-500'    },
}

export function toDateStr(d: Date): string {
  return d.toISOString().slice(0, 10)
}

export function parseDateStr(s: string): Date {
  const [y, m, day] = s.split('-').map(Number)
  return new Date(y, m - 1, day)
}

export function isSameDay(a: Date, b: Date): boolean {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
}

export function daysBetween(start: Date, end: Date): number {
  return Math.round((end.getTime() - start.getTime()) / 86400000)
}


export function calendarGridDays(year: number, month: number): (Date | null)[] {
  const firstDay = new Date(year, month - 1, 1)
  const daysInMonth = new Date(year, month, 0).getDate()
  const startOffset = firstDay.getDay()

  const gridDays: (Date | null)[] = []
  for (let i = 0; i < startOffset; i++) gridDays.push(null)
  for (let d = 1; d <= daysInMonth; d++) gridDays.push(new Date(year, month - 1, d))
  while (gridDays.length % 7 !== 0) gridDays.push(null)
  return gridDays
}

export function eventsForCalendarDay(events: CalendarEvent[], day: Date): CalendarEvent[] {
  const dayStr = toDateStr(day)
  return events.filter((e) => {
    const start = e.startDate.slice(0, 10)
    const end = e.endDate.slice(0, 10)
    return start <= dayStr && dayStr < end
  })
}

export function selectedBlockRange(selectStart: string, clickedDay: Date): { startDate: string; endDate: string } {
  const clicked = toDateStr(clickedDay)
  const start = selectStart < clicked ? selectStart : clicked
  const end = selectStart < clicked ? clicked : selectStart
  return {
    startDate: start,
    endDate: toDateStr(new Date(parseDateStr(end).getTime() + 86400000)),
  }
}


export default function VehicleCalendar({ vehicleId }: Props) {
  const { dict, language } = useDashboardI18n()
  const c = dict.calendar
  const today = new Date()
  const [year,  setYear]  = useState(today.getFullYear())
  const [month, setMonth] = useState(today.getMonth() + 1)
  const [events, setEvents]    = useState<CalendarEvent[]>([])
  const [loading, setLoading]  = useState(true)
  const [error, setError]      = useState<string | null>(null)

  // Block-creation modal
  const [showModal, setShowModal]       = useState(false)
  const [blockStart, setBlockStart]     = useState('')
  const [blockEnd,   setBlockEnd]       = useState('')
  const [blockReason, setBlockReason]   = useState('')
  const [blockType,   setBlockType]     = useState<'MANUAL' | 'MAINTENANCE'>('MANUAL')
  const [saving, setSaving]             = useState(false)
  const [saveError, setSaveError]       = useState<string | null>(null)

  // Day-click selection for quick create
  const [selectStart, setSelectStart]   = useState<string | null>(null)

  const fetchCalendar = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await apiFetch<CalendarEvent[]>(
        `/vehicles/${vehicleId}/calendar?year=${year}&month=${month}`
      )
      setEvents(data)
    } catch (e: any) {
      setError(e.message ?? c.failedLoad)
    } finally {
      setLoading(false)
    }
  }, [vehicleId, year, month, c])

  useEffect(() => { fetchCalendar() }, [fetchCalendar])

  const prevMonth = () => {
    if (month === 1) { setYear(y => y - 1); setMonth(12) }
    else setMonth(m => m - 1)
  }
  const nextMonth = () => {
    if (month === 12) { setYear(y => y + 1); setMonth(1) }
    else setMonth(m => m + 1)
  }

  // Build calendar grid (6 rows × 7 cols)
  const gridDays = calendarGridDays(year, month)

  // Map events to date strings for fast lookup
  const eventsOnDay = (day: Date): CalendarEvent[] => eventsForCalendarDay(events, day)

  const isToday = (day: Date) => isSameDay(day, today)

  const handleDayClick = (day: Date) => {
    const str = toDateStr(day)
    if (!selectStart) {
      setSelectStart(str)
    } else {
      const range = selectedBlockRange(selectStart, day)
      setBlockStart(range.startDate)
      setBlockEnd(range.endDate)
      setSelectStart(null)
      setShowModal(true)
    }
  }

  const openModal = () => {
    setBlockStart('')
    setBlockEnd('')
    setBlockReason('')
    setBlockType('MANUAL')
    setSaveError(null)
    setShowModal(true)
  }

  const closeModal = () => {
    setShowModal(false)
    setSaveError(null)
    setSelectStart(null)
  }

  const handleSaveBlock = async () => {
    if (!blockStart || !blockEnd) { setSaveError(c.datesRequired); return }
    if (blockEnd <= blockStart)   { setSaveError(c.endAfterStart); return }
    setSaving(true)
    setSaveError(null)
    try {
      await apiFetch(`/vehicles/${vehicleId}/calendar/blocks`, {
        method: 'POST',
        body: JSON.stringify({ startDate: blockStart, endDate: blockEnd, reason: blockReason || undefined, type: blockType }),
      })
      setShowModal(false)
      fetchCalendar()
    } catch (e: any) {
      setSaveError(e.message ?? c.failedCreateBlock)
    } finally {
      setSaving(false)
    }
  }

  const handleDeleteBlock = async (id: string) => {
    if (!confirm(c.removeBlockConfirm)) return
    try {
      await apiFetch(`/vehicles/${vehicleId}/calendar/blocks/${id}`, { method: 'DELETE' })
      fetchCalendar()
    } catch (e: any) {
      alert(e.message ?? c.failedDeleteBlock)
    }
  }

  const localeCode = language === 'fr' ? 'fr-FR' : language === 'ar' ? 'ar-MA' : 'en-US'
  const monthLabel = new Date(year, month - 1, 1).toLocaleDateString(localeCode, { month: 'long', year: 'numeric' })

  // Separate reservations vs blocks for the legend/list below
  const reservationEvents = events.filter((e) => e.type === 'RESERVATION')
  const blockEvents        = events.filter((e) => e.type !== 'RESERVATION')

  return (
    <div className="card p-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <CalendarDays className="w-5 h-5 text-slate-600" />
          <h3 className="text-base font-semibold text-slate-900">{c.heading}</h3>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={prevMonth} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors">
            <ChevronLeft className="w-4 h-4" />
          </button>
          <span className="text-sm font-medium text-slate-700 min-w-[130px] text-center">{monthLabel}</span>
          <button onClick={nextMonth} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors">
            <ChevronRight className="w-4 h-4" />
          </button>
          <button onClick={openModal} className="ml-2 btn-primary flex items-center gap-1.5 text-xs py-1.5 px-3">
            <Plus className="w-3.5 h-3.5" /> {c.blockDates}
          </button>
        </div>
      </div>

      {selectStart && (
        <div className="text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded-lg px-3 py-2">
          {c.clickSecondDay(selectStart!)}
          <button className="ml-2 underline" onClick={() => setSelectStart(null)}>{c.cancelSelection}</button>
        </div>
      )}

      {/* Legend */}
      <div className="flex flex-wrap gap-4 text-xs text-slate-600">
        <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-blue-500 inline-block" />{c.legendReserved}</span>
        <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-orange-500 inline-block" />{c.legendMaintenance}</span>
        <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-red-500 inline-block" />{c.legendBlocked}</span>
        <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block" />{c.legendAvailable}</span>
      </div>

      {error && <div className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">{error}</div>}

      {/* Calendar grid */}
      <div className={loading ? 'opacity-50 pointer-events-none' : ''}>
        {/* Day headers */}
        <div className="grid grid-cols-7 mb-1">
          {c.dayHeaders.map((d) => (
            <div key={d} className="text-center text-xs font-medium text-slate-400 py-1">{d}</div>
          ))}
        </div>

        {/* Day cells */}
        <div className="grid grid-cols-7 gap-px bg-slate-100 rounded-xl overflow-hidden border border-slate-100">
          {gridDays.map((day, i) => {
            if (!day) return <div key={`empty-${i}`} className="bg-white min-h-[72px]" />

            const dayEvents = eventsOnDay(day)
            const isSelected = selectStart === toDateStr(day)
            const isPast = day < today && !isToday(day)

            return (
              <div
                key={toDateStr(day)}
                onClick={() => handleDayClick(day)}
                className={[
                  'bg-white min-h-[72px] p-1.5 cursor-pointer transition-colors',
                  isToday(day) ? 'ring-2 ring-inset ring-blue-500' : '',
                  isSelected ? 'bg-blue-50' : 'hover:bg-slate-50',
                  isPast ? 'opacity-60' : '',
                ].filter(Boolean).join(' ')}
              >
                <div className={[
                  'text-xs font-medium mb-1 w-6 h-6 flex items-center justify-center rounded-full',
                  isToday(day) ? 'bg-blue-500 text-white' : 'text-slate-700',
                ].join(' ')}>
                  {day.getDate()}
                </div>

                <div className="space-y-0.5">
                  {dayEvents.slice(0, 2).map((ev) => {
                    const s = EVENT_STYLES[ev.type]
                    return (
                      <div key={ev.id} className={`text-[10px] leading-tight px-1 py-0.5 rounded truncate ${s.bg} ${s.text}`}>
                        {ev.label}
                      </div>
                    )
                  })}
                  {dayEvents.length > 2 && (
                    <div className="text-[10px] text-slate-400 pl-1">{c.moreDays(dayEvents.length - 2)}</div>
                  )}
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* Events list for this month */}
      {(reservationEvents.length > 0 || blockEvents.length > 0) && (
        <div className="space-y-3 pt-2">
          {reservationEvents.length > 0 && (
            <div>
              <p className="text-xs font-medium text-slate-500 uppercase tracking-wide mb-2">{c.reservationsThisMonth}</p>
              <div className="space-y-1.5">
                {reservationEvents.map((e) => {
                  const s = EVENT_STYLES[e.type]
                  const start = e.startDate.slice(0, 10)
                  const end   = e.endDate.slice(0, 10)
                  const days  = daysBetween(parseDateStr(start), parseDateStr(end))
                  return (
                    <div key={e.id} className={`flex items-center justify-between px-3 py-2 rounded-lg border text-sm ${s.bg} ${s.border}`}>
                      <div className="flex items-center gap-2">
                        <span className={`w-2 h-2 rounded-full ${s.dot}`} />
                        <span className={`font-medium ${s.text}`}>{e.label}</span>
                        <span className={`text-xs ${s.text} opacity-70`}>{start} → {end} ({days}d)</span>
                      </div>
                      <span className={`text-xs px-2 py-0.5 rounded-full bg-white/60 ${s.text}`}>{e.status}</span>
                    </div>
                  )
                })}
              </div>
            </div>
          )}

          {blockEvents.length > 0 && (
            <div>
              <p className="text-xs font-medium text-slate-500 uppercase tracking-wide mb-2">{c.blocksAndMaintenance}</p>
              <div className="space-y-1.5">
                {blockEvents.map((e) => {
                  const s = EVENT_STYLES[e.type]
                  const start = e.startDate.slice(0, 10)
                  const end   = e.endDate.slice(0, 10)
                  const days  = daysBetween(parseDateStr(start), parseDateStr(end))
                  const Icon  = e.type === 'MAINTENANCE' ? Wrench : Ban
                  return (
                    <div key={e.id} className={`flex items-center justify-between px-3 py-2 rounded-lg border text-sm ${s.bg} ${s.border}`}>
                      <div className="flex items-center gap-2">
                        <Icon className={`w-3.5 h-3.5 ${s.text}`} />
                        <span className={`font-medium ${s.text}`}>{e.label}</span>
                        <span className={`text-xs ${s.text} opacity-70`}>{start} → {end} ({days}d)</span>
                      </div>
                      <button
                        onClick={() => handleDeleteBlock(e.id)}
                        className={`p-1 rounded hover:bg-white/60 transition-colors ${s.text}`}
                        title={c.removeBlock}
                      >
                        <X className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  )
                })}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Add Block Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-blue-950/40 backdrop-blur-sm" onClick={closeModal}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 space-y-4" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between">
              <h4 className="text-base font-semibold text-slate-900">{c.modalTitle}</h4>
              <button onClick={closeModal} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100">
                <X className="w-4 h-4" />
              </button>
            </div>

            <div className="space-y-3 text-sm">
              <div>
                <label className="block text-xs font-medium text-slate-500 mb-1.5">{c.blockTypeLabel}</label>
                <div className="flex gap-2">
                  <button
                    onClick={() => setBlockType('MANUAL')}
                    className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-lg border text-sm font-medium transition-colors ${blockType === 'MANUAL' ? 'bg-red-50 border-red-300 text-red-700' : 'border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                  >
                    <Ban className="w-3.5 h-3.5" /> {c.manualBlock}
                  </button>
                  <button
                    onClick={() => setBlockType('MAINTENANCE')}
                    className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-lg border text-sm font-medium transition-colors ${blockType === 'MAINTENANCE' ? 'bg-orange-50 border-orange-300 text-orange-700' : 'border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                  >
                    <Wrench className="w-3.5 h-3.5" /> {c.maintenanceBlock}
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{c.startDate}</label>
                  <input
                    type="date"
                    className="input-field"
                    value={blockStart}
                    onChange={(e) => setBlockStart(e.target.value)}
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{c.endDate}</label>
                  <input
                    type="date"
                    className="input-field"
                    value={blockEnd}
                    min={blockStart}
                    onChange={(e) => setBlockEnd(e.target.value)}
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-medium text-slate-500 mb-1.5">{c.reasonLabel} <span className="font-normal">{c.optional}</span></label>
                <input
                  type="text"
                  className="input-field"
                  placeholder={blockType === 'MAINTENANCE' ? c.reasonPlaceholderMaintenance : c.reasonPlaceholderManual}
                  value={blockReason}
                  onChange={(e) => setBlockReason(e.target.value)}
                />
              </div>
            </div>

            {saveError && (
              <div className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">{saveError}</div>
            )}

            <div className="flex gap-2 pt-1">
              <button onClick={closeModal} className="flex-1 btn-secondary">{c.cancel}</button>
              <button onClick={handleSaveBlock} disabled={saving} className="flex-1 btn-primary">
                {saving ? c.saving : c.saveBlock}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
