"use client"
import React from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useModifyAppointment } from "@/lib/react-query/hooks/appointments"
import { useCreateBooking } from "@/lib/react-query/hooks/bookings"
import { useGetStylistById } from "@/lib/react-query/hooks/stylists"
import { useToaster } from "@/context/ToasterContext"
import { BookingDateTimeFields } from "./BookingDateTimeFields"
import { TimeSuggestions } from "./TimeSuggestions"
import { useTranslations, useFormatter } from "next-intl"
import { transformAvailabilityToSuggestions } from "@/lib/utils"
import { Edit } from "lucide-react"
import FullEditBookingModal from "./FullEditBookingModal"

const errorInputClass = "h-12 border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200 px-2 py-4 text-base"
const normalInputClass = "h-12 border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20 px-2 py-4 text-base"

interface Appointment {
  id: number
  bookingId: string
  staffId: number
  date: Date
  startTime: string
  endTime: string
  clientName: string
  service: string
  status: string
  color: "cyan" | "orange" | "teal" | "pink"
  generatedBy?: string
  clientId?: string
  serviceId?: string
  salonId?: string
  realStylistId?: string
  offerId?: string
}

interface UpdateBookingModalProps {
  open: boolean
  setOpen: (open: boolean) => void
  appointment: Appointment | null
  services?: { value: string; label: string; description: string }[]
  clients?: { value: string; label: string; description: string }[]
  onSuccess?: () => void
}

export default function UpdateBookingModal({ open, setOpen, appointment, services, clients, onSuccess }: UpdateBookingModalProps) {
  const modifyAppointmentMutation = useModifyAppointment()
  const toast = useToaster()
  const t = useTranslations()
  const formatter = useFormatter()
  const { data: stylistDetail } = useGetStylistById(appointment?.realStylistId || "")

  const [dateTimeFields, setDateTimeFields] = React.useState<{
    date: Date | undefined
    startTime: string
  }>({
    date: undefined,
    startTime: ""
  })
  const [dateTimeError, setDateTimeError] = React.useState<string>("")
  const [timeSuggestions, setTimeSuggestions] = React.useState<{
    message: string
    suggestions: any[]
  } | null>(null)

  // Update form when appointment changes
  React.useEffect(() => {
    if (appointment && open) {
      // Extract local time (HH:mm) from the ISO string if it's in ISO format
      let formattedTime = appointment.startTime
      if (appointment.startTime.includes('T')) {
        const startDate = new Date(appointment.startTime)
        if (!isNaN(startDate.getTime())) {
          formattedTime = `${startDate.getHours().toString().padStart(2, "0")}:${startDate.getMinutes().toString().padStart(2, "0")}`
        }
      }

      setDateTimeFields({
        date: appointment.date,
        startTime: formattedTime
      })
    }
  }, [appointment, open])

  const handleSelectSuggestedTime = (date: Date, startTime: string, stylistId: string) => {
    // Update both the date and time fields with the selected suggestion
    setDateTimeFields({
      date,
      startTime
    })
    // Clear suggestions
    setTimeSuggestions(null)
    // Clear any previous errors
    setDateTimeError("")
  }

  const handleCancelSuggestions = () => {
    setTimeSuggestions(null)
  }

  const handleSubmit = () => {
    if (!appointment) return

    // Validate date and time fields for update
    if (!dateTimeFields.date || !dateTimeFields.startTime) {
      setDateTimeError(t("calendar.validation.selectDateTime"))
      return
    }
    setDateTimeError("")

    const newDate = `${dateTimeFields.date.getFullYear()}-${String(dateTimeFields.date.getMonth() + 1).padStart(2, "0")}-${String(dateTimeFields.date.getDate()).padStart(2, "0")}`

    modifyAppointmentMutation.mutate({
      bookingId: appointment.bookingId,
      date: newDate,
      time: dateTimeFields.startTime,
      delete: false
    }, {
      onSuccess: (response) => {
        if (response?.suggestions) {
          const suggestions = response.suggestions
          const message = response.message || t("calendar.timeSuggestions.description")

          toast.showInfo(message)
          setTimeSuggestions({
            message,
            suggestions
          })

          return
        }
        setOpen(false)
        onSuccess?.()
      },
      onError: (error: any) => {
        const data = error.response?.data
        if (data?.reason === "SLOT_NOT_AVAILABLE" && data?.availability) {
          const suggestions = transformAvailabilityToSuggestions(data.availability)
          setTimeSuggestions({
            message: t("calendar.timeSuggestions.description"),
            suggestions
          })
          return
        }
      }
    })
  }

  const [isFullEditOpen, setIsFullEditOpen] = React.useState(false)

  const handleSpecialEdit = () => {
    setIsFullEditOpen(true)
  }

  if (!appointment) return null

  return (
    <>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="w-[689px]! sm:max-w-[689px] bg-white border-0 max-h-[90vh] overflow-y-auto [&>button]:top-5 [&>button]:right-5 [&>button]:text-white [&>button]:hover:text-gray-200 [&>button>svg]:stroke-[4px]">
          <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("calendar.modals.updateBooking")}</DialogTitle>
          </DialogHeader>

          <div className="space-y-4 px-1 max-h-[70vh] overflow-y-auto">
            {/* Current Appointment Info */}
            <div className="bg-gray-50 p-4 rounded-lg">
              <div className="flex justify-between items-center mb-2">
                <h3 className="font-medium text-gray-900">{t("calendar.modals.currentAppointment")}</h3>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 hover:bg-gray-200"
                  onClick={handleSpecialEdit}
                >
                  <Edit className="h-4 w-4 text-primary-blue" />
                </Button>
              </div>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="font-medium">{t("calendar.modals.client")}</span> {appointment.clientName}
                </div>
                <div>
                  <span className="font-medium">{t("calendar.modals.service")}</span> {appointment.service}
                </div>
                <div>
                  <span className="font-medium">{t("calendar.modals.date")}</span> {formatter.dateTime(appointment.date, { day: '2-digit', month: 'long', year: 'numeric' })}
                </div>
                <div>
                  <span className="font-medium">{t("calendar.modals.time")}</span> {(() => {
                    const formatLocalTime = (isoString: string) => {
                      const d = new Date(isoString)
                      if (isNaN(d.getTime())) return isoString

                      const hours = d.getHours().toString().padStart(2, "0")
                      const minutes = d.getMinutes().toString().padStart(2, "0")
                      return `${hours}:${minutes}`
                    }
                    return `${formatLocalTime(appointment.startTime)} - ${formatLocalTime(appointment.endTime)}`
                  })()}
                </div>
                <div className="col-span-2">
                  <span className="font-medium">{t("calendar.modals.status")}</span>
                  <span className={`ml-1 px-2 py-1 rounded text-xs font-medium ${appointment.status === 'confirmed'
                    ? 'bg-green-100 text-green-800'
                    : appointment.status === 'cancelled'
                      ? 'bg-red-100 text-red-800'
                      : (appointment.status === 'no-show' || appointment.status === 'no_show')
                        ? 'bg-orange-100 text-orange-800'
                        : 'bg-blue-100 text-blue-800'
                    }`}>
                    {t(`calendar.status.${appointment.status}`)}
                  </span>
                </div>
              </div>
            </div>

            {/* Date & Time Fields */}
            <BookingDateTimeFields
              value={dateTimeFields}
              onChange={setDateTimeFields}
              dateError={dateTimeError && !dateTimeFields.date ? dateTimeError : undefined}
              workingHours={stylistDetail?.workingHours}
              vacations={stylistDetail?.vacations}
              stylistName={stylistDetail?.name}
            />

            {/* Time Suggestions */}
            {timeSuggestions && (
              <div className="border-t pt-4">
                <TimeSuggestions
                  suggestions={timeSuggestions.suggestions}
                  onSelectTime={handleSelectSuggestedTime}
                  onCancel={handleCancelSuggestions}
                />
              </div>
            )}

            {/* Actions */}
            <DialogFooter className="flex justify-end w-full mt-4">
              <div className="flex gap-4 mt-2">
                <Button
                  variant="outline"
                  type="button"
                  onClick={() => setOpen(false)}
                  className="flex-1 bg-transparent border-blue-950 text-blue-950 rounded-sm px-8"
                >
                  {t("calendar.buttons.cancel")}
                </Button>
                <Button
                  onClick={handleSubmit}
                  className="flex-1 bg-primary-gradient text-white rounded-sm px-8"
                  disabled={modifyAppointmentMutation.isPending}
                >
                  {modifyAppointmentMutation.isPending
                    ? t("calendar.buttons.updating")
                    : t("calendar.buttons.updateBooking")
                  }
                </Button>
              </div>
            </DialogFooter>
          </div>
        </DialogContent>
      </Dialog>

      <FullEditBookingModal
        open={isFullEditOpen}
        setOpen={(isOpen) => {
          setIsFullEditOpen(isOpen)
          if (!isOpen) {
            // If full edit is closed, we might want to close the original one too if update was successful
            // But we'll leave it to the success handler
          }
        }}
        appointment={appointment}
        services={services}
        clients={clients}
        onSuccess={() => {
          setIsFullEditOpen(false)
          setOpen(false) // Close the original update modal as well
          onSuccess?.()
        }}
      />
    </>
  )
}