"use client"
import React, { useState, useEffect } from "react"
import { Plus, Trash2, Copy, ChevronDown } from "lucide-react"
import { TimeInput } from "@/components/common/TimeInput"
import { useToaster } from "@/context/ToasterContext"
import { useTranslations } from "next-intl"

const daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

export interface TimeSlot {
  start: string
  end: string
}

export interface DaySchedule {
  enabled: boolean
  timeSlots: TimeSlot[]
}

export interface WorkingHoursFormProps {
  value?: Record<string, DaySchedule>
  onChange?: (schedule: Record<string, DaySchedule>) => void
  className?: string
}

interface SwitchProps {
  checked: boolean
  onChange: () => void
  onClick?: (e: React.MouseEvent) => void
}

interface ButtonProps {
  children: React.ReactNode
  onClick: () => void
  variant?: "default" | "destructive"
  className?: string
  type?: "button" | "submit" | "reset"
}

interface AccordionItemProps {
  day: string
  schedule: DaySchedule
  isOpen: boolean
  onToggle: () => void
  onToggleDay: () => void
  onUpdateTimeSlot: (index: number, field: "start" | "end", value: string) => void
  onAddTimeSlot: () => void
  onRemoveTimeSlot: (index: number) => void
  onCopyToAll?: () => void
  error?: string
}

// Custom Switch Component
const Switch: React.FC<SwitchProps> = ({ checked, onChange, onClick }) => (
  <button
    type="button"
    role="switch"
    aria-checked={checked}
    onClick={e => {
      onClick?.(e)
      onChange()
    }}
    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${checked ? "bg-blue-950" : "bg-gray-300"}`}
  >
    <span
      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${checked ? "translate-x-6" : "translate-x-1"}`}
    />
  </button>
)

// Custom Button Component
const Button: React.FC<ButtonProps> = ({ children, onClick, variant = "default", className, type = "button" }) => {
  const baseClass = "inline-flex items-center justify-center transition-colors"
  const variantClass = variant === "destructive" ? "bg-red-500 hover:bg-red-600 text-white" : "bg-blue-950 text-white hover:bg-blue-900"

  return (
    <button type={type} onClick={onClick} className={`${baseClass} ${variantClass} ${className}`}>
      {children}
    </button>
  )
}

// Custom Accordion Item Component
const AccordionItem: React.FC<AccordionItemProps> = ({
  day,
  schedule,
  isOpen,
  onToggle,
  onToggleDay,
  onUpdateTimeSlot,
  onAddTimeSlot,
  onRemoveTimeSlot,
  onCopyToAll,
  error
}) => {
  const t = useTranslations()

  // Safety check - if schedule is undefined, return null
  if (!schedule) {
    return null
  }
  return (
    <div className="border overflow-hidden border-blue-950 rounded-lg mb-3 bg-white">
      {/* Accordion Header */}
      <div
        onClick={onToggle}
        className="w-full px-4 py-3 flex items-center justify-between cursor-pointer hover:bg-gray-100 transition-colors"
        role="button"
        tabIndex={0}
        onKeyDown={e => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault()
            onToggle()
          }
        }}
      >
        <div className="flex items-center gap-3 flex-1">
          <Switch checked={schedule.enabled} onChange={onToggleDay} onClick={e => e.stopPropagation()} />
          <span className="font-semibold text-blue-950 text-base">{t(`staff.workingHours.${day.toLowerCase()}`)}</span>
        </div>
        <ChevronDown className={`h-5 w-5 text-blue-950 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`} />
      </div>

      {/* Accordion Content */}
      <div className={`overflow-hidden transition-all duration-200 ${isOpen ? "max-h-[1000px] opacity-100" : "max-h-0 opacity-0"}`}>
        {schedule.enabled && (
          <div className="px-4 pb-4 pt-2 space-y-3">
            {schedule.timeSlots.map((slot, index) => (
              <div key={index} className="space-y-2">
                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <TimeInput
                      value={slot.start}
                      onChange={(value: string) => onUpdateTimeSlot(index, "start", value)}
                      className="w-full h-10 pl-2 pr-12 text-base border border-blue-950 rounded-lg focus:border-blue-950 focus:ring-2 focus:ring-blue-950/20 outline-none"
                    />
                  </div>
                  <span className="text-gray-500 text-base">{t("workingHoursForm.to")}</span>
                  <div className="relative flex-1">
                    <TimeInput
                      value={slot.end}
                      onChange={(value: string) => onUpdateTimeSlot(index, "end", value)}
                      className="w-full h-10 pl-2 pr-12 text-base border border-blue-950 rounded-lg focus:border-blue-950 focus:ring-2 focus:ring-blue-950/20 outline-none"
                    />
                  </div>
                  <div className="flex gap-2">
                    <Button onClick={() => onAddTimeSlot()} className="bg-primary-gradient h-10 w-10 rounded-full">
                      <Plus className="h-5 w-5" />
                    </Button>
                    {schedule.timeSlots.length > 1 && (
                      <Button variant="destructive" onClick={() => onRemoveTimeSlot(index)} className="h-10 w-10 rounded-full">
                        <Trash2 className="h-5 w-5" />
                      </Button>
                    )}
                  </div>
                </div>
              </div>
            ))}
            {day === "monday" && onCopyToAll && (
              <div
                className="flex items-center gap-2 pt-1 cursor-pointer select-none text-blue-950"
                onClick={onCopyToAll}
                role="button"
                tabIndex={0}
                aria-label="Copy timings to all days"
              >
                <Copy className="h-5 w-5 text-blue-900" />
                <span className="text-base font-medium">{t("workingHoursForm.copyMondayToAll")}</span>
              </div>
            )}
            {error && <div className="text-red-500 text-sm mt-2">{error}</div>}
          </div>
        )}
      </div>
    </div>
  )
}

// Main Working Hours Form Component
export function WorkingHoursForm({ value, onChange, className = "" }: WorkingHoursFormProps) {
  const t = useTranslations()
  const { showSuccess } = useToaster()

  const getDefaultSchedule = () => ({
    monday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    tuesday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    wednesday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    thursday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    friday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    saturday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    },
    sunday: {
      enabled: true,
      timeSlots: [{ start: "09:00", end: "21:00" }]
    }
  })

  const [schedule, setSchedule] = useState<Record<string, DaySchedule>>(() => {
    const defaultSchedule = getDefaultSchedule()
    if (value) {
      // Merge provided value with defaults, ensuring all days exist
      return { ...defaultSchedule, ...value }
    }
    return defaultSchedule
  })

  useEffect(() => {
    if (value) {
      const defaultSchedule = getDefaultSchedule()
      setSchedule({ ...defaultSchedule, ...value })
    }
  }, [value])


  const [openDays, setOpenDays] = useState<string[]>(["monday"])
  const [errors, setErrors] = useState<Record<string, string>>({})

  const toMinutes = (time: string) => {
    const [h, m] = time.split(":").map(Number)
    return h * 60 + m
  }

  const hasOverlap = (slots: TimeSlot[], newSlot: TimeSlot, excludeIndex?: number) => {
    const newStart = toMinutes(newSlot.start)
    const newEnd = toMinutes(newSlot.end)
    return slots.some((slot, index) => {
      if (excludeIndex !== undefined && index === excludeIndex) return false
      const start = toMinutes(slot.start)
      const end = toMinutes(slot.end)
      return newStart < end && start < newEnd
    })
  }

  const updateSchedule = (newSchedule: Record<string, DaySchedule>) => {
    setSchedule(newSchedule)
    onChange?.(newSchedule)
  }

  const toggleDay = (day: string) => {
    const newSchedule = {
      ...schedule,
      [day]: {
        ...schedule[day],
        enabled: !schedule[day].enabled
      }
    }
    updateSchedule(newSchedule)
    setErrors(prev => ({ ...prev, [day]: "" }))
  }

  const updateTimeSlot = (day: string, index: number, field: "start" | "end", value: string) => {
    const updatedSlots = schedule[day].timeSlots.map((slot, i) => (i === index ? { ...slot, [field]: value } : slot))
    const updatedSlot = updatedSlots[index]

    // Check if end time is before start time
    if (toMinutes(updatedSlot.end) <= toMinutes(updatedSlot.start)) {
      setErrors(prev => ({ ...prev, [day]: t("workingHoursForm.errors.endTimeAfterStart") }))
      return
    }

    if (hasOverlap(updatedSlots, updatedSlot, index)) {
      setErrors(prev => ({ ...prev, [day]: t("workingHoursForm.errors.timeSlotOverlap") }))
      return
    }
    const newSchedule = {
      ...schedule,
      [day]: {
        ...schedule[day],
        timeSlots: updatedSlots
      }
    }
    updateSchedule(newSchedule)
    setErrors(prev => ({ ...prev, [day]: "" }))
  }

  const addTimeSlot = (day: string) => {
    const existingSlots = schedule[day].timeSlots
    const lastEndTime = existingSlots.length > 0 ? existingSlots[existingSlots.length - 1].end : "09:00"
    const newStart = lastEndTime
    const newEnd = toMinutes(lastEndTime) + 60 // Add 1 hour
    const newEndTime = `${Math.floor(newEnd / 60)
      .toString()
      .padStart(2, "0")}:${(newEnd % 60).toString().padStart(2, "0")}`
    const newSlot = { start: newStart, end: newEndTime }

    // Ensure end > start (should always be true, but just in case)
    if (toMinutes(newSlot.end) <= toMinutes(newSlot.start)) {
      setErrors(prev => ({ ...prev, [day]: t("workingHoursForm.errors.endTimeAfterStart") }))
      return
    }

    if (hasOverlap(existingSlots, newSlot)) {
      setErrors(prev => ({ ...prev, [day]: t("workingHoursForm.errors.timeSlotOverlap") }))
      return
    }
    const newSchedule = {
      ...schedule,
      [day]: {
        ...schedule[day],
        timeSlots: [...existingSlots, newSlot]
      }
    }
    updateSchedule(newSchedule)
    setErrors(prev => ({ ...prev, [day]: "" }))
  }

  const removeTimeSlot = (day: string, index: number) => {
    const newSchedule = {
      ...schedule,
      [day]: {
        ...schedule[day],
        timeSlots: schedule[day].timeSlots.filter((_, i) => i !== index)
      }
    }
    updateSchedule(newSchedule)
    setErrors(prev => ({ ...prev, [day]: "" }))
  }

  const applyMondayToAll = () => {
    const mondaySchedule = schedule.monday
    const newSchedule: Record<string, DaySchedule> = {}

    daysOfWeek.forEach(day => {
      newSchedule[day] = {
        enabled: true,
        timeSlots: mondaySchedule.timeSlots.map(slot => ({
          start: slot.start,
          end: slot.end
        }))
      }
    })

    updateSchedule(newSchedule)
    setOpenDays(daysOfWeek) // Open all days
    showSuccess(t("workingHoursForm.copyMondayToAll"))
  }

  return (
    <div className={`w-full max-w-2xl mx-auto rounded-lg ${className}`}>
      <div className="pb-2">
        {daysOfWeek.map(day => (
          <AccordionItem
            key={day}
            day={day}
            schedule={schedule[day]}
            isOpen={openDays.includes(day)}
            onToggle={() => {
              if (openDays.includes(day)) {
                setOpenDays(openDays.filter(d => d !== day))
              } else {
                setOpenDays([...openDays, day])
              }
            }}
            onToggleDay={() => toggleDay(day)}
            onUpdateTimeSlot={(index, field, value) => updateTimeSlot(day, index, field, value)}
            onAddTimeSlot={() => addTimeSlot(day)}
            onRemoveTimeSlot={index => removeTimeSlot(day, index)}
            onCopyToAll={day === "monday" ? applyMondayToAll : undefined}
            error={errors[day]}
          />
        ))}
      </div>
    </div>
  )
}
