"use client"
import React, { useState } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { WorkingHoursForm } from "@/components/common/WorkingHoursForm"
import { Button } from "@/components/ui/button"
import { useTranslations } from "next-intl"

interface WorkingHoursModalProps {
  open: boolean
  setOpen: (open: boolean) => void
  onSave?: (workingHours: any[]) => void
  initialSchedule?: Record<string, any>
}

export default function AddWorkingHoursModal({ open, setOpen, onSave, initialSchedule }: WorkingHoursModalProps) {
  const t = useTranslations()
  const [schedule, setSchedule] = useState<Record<string, any>>(
    () =>
      initialSchedule || {
        monday: { enabled: true, timeSlots: [{ start: "09:00", end: "18:00" }] },
        tuesday: { enabled: true, timeSlots: [{ start: "09:00", end: "18:00" }] },
        wednesday: { enabled: true, timeSlots: [{ start: "09:00", end: "18:00" }] },
        thursday: { enabled: true, timeSlots: [{ start: "09:00", end: "18:00" }] },
        friday: { enabled: true, timeSlots: [{ start: "09:00", end: "18:00" }] },
        saturday: { enabled: false, timeSlots: [{ start: "09:00", end: "18:00" }] },
        sunday: { enabled: false, timeSlots: [{ start: "09:00", end: "18:00" }] }
      }
  )

  const handleSave = () => {
    // Transform the schedule data to the API format
    const transformedWorkingHours = Object.entries(schedule).map(([day, scheduleData]: [string, any]) => ({
      day: day.toLowerCase(),
      enabled: scheduleData.enabled,
      slots: scheduleData.timeSlots
    }))

    if (onSave) {
      onSave(transformedWorkingHours)
    }
    setOpen(false)
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-[600px] bg-white border-0 max-h-[90vh] overflow-hidden [&>button]:top-4 [&>button]:right-4 [&>button]:text-white [&>button]:hover:text-gray-200">
        <DialogHeader className="bg-primary-gradient -m-6 mb-0 px-6 py-3 rounded-t-lg">
          <DialogTitle className="text-white text-lg font-medium">{t("staff.modals.addWorkingHours")}</DialogTitle>
        </DialogHeader>

        <div className="overflow-y-auto max-h-[calc(90vh-160px)] px-1 py-4">
          <WorkingHoursForm value={schedule} onChange={setSchedule} />
        </div>

        <DialogFooter className="flex justify-end gap-2 pt-4 border-t">
          <Button variant="outline" onClick={() => setOpen(false)} className="px-8 border-blue-950">
            {t("common.cancel")}
          </Button>
          <Button onClick={handleSave} className="px-8 bg-primary-gradient text-white">
            {t("common.save")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
