"use client"
import { useState, useMemo, useEffect } from "react"
import { CustomTabs, TabItem, TabsContent } from "@/components/common/CustomTabs"
import { CalendarGrid } from "./CalendarGrid"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { Calendar } from "@/components/ui/calendar"
import { enUS, fr } from "react-day-picker/locale"
import { Card, CardContent } from "@/components/ui/card"
import { startOfWeek, endOfWeek, startOfMonth, endOfMonth } from "date-fns"
import { useGetStylists } from "@/lib/react-query/hooks/stylists"
import { useGetAppointments } from "@/lib/react-query/hooks/appointments"
import { useGetServices } from "@/lib/react-query/hooks/services"
import { useGetClients } from "@/lib/react-query/hooks/clients"
import { Autocomplete } from "@/components/common/Autocomplete"
import { useQueryStates } from "@/hooks/use-query-state"
import { useAuth } from "@/context/AuthContext"
import { useTranslations, useLocale } from "next-intl"

interface StaffMember {
  id: number
  name: string
  avatar: string
}

interface Appointment {
  id: number
  bookingId: string
  staffId: number
  date: Date
  dateKey: string
  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 CalenderTabsProps {
  onAppointmentUpdate?: () => void
}

// Format local Date object to YYYY-MM-DD without timezone conversion
const formatLocalDate = (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}`
}

// Convert UTC ISO string to user's timezone date (YYYY-MM-DD)
const utcToUserDate = (utcString: string, timeZone: string) => {
  const date = new Date(utcString)
  return date.toLocaleDateString("en-CA", { timeZone })
}

export function CalenderTabs({ onAppointmentUpdate }: CalenderTabsProps) {
  const [date, setDate] = useState<Date | undefined>(new Date())
  const [datePickerOpen, setDatePickerOpen] = useState(false)

  const { data: stylists, isLoading: isLoadingStylists } = useGetStylists()
  const { data: servicesData } = useGetServices({ status: "active" })
  const { data: clientsData_raw } = useGetClients()
  const t = useTranslations()
  const locale = useLocale()
  const { user } = useAuth()

  const calendarLocale = locale === 'fr' ? fr : enUS

  // Utility function to get hour in user's timezone
  const getHourInTimeZone = (isoString: string, timeZone: string): string => {
    const date = new Date(isoString)
    const parts = new Intl.DateTimeFormat("en-US", {
      timeZone,
      hour: "2-digit",
      hour12: false
    }).formatToParts(date)
    const hour = parts.find(p => p.type === "hour")?.value || "00"
    return `${hour}:00`
  }

  const queryStates = useQueryStates({
    activeTab: {
      key: 'tab',
      defaultValue: 'daily' as 'daily' | 'weekly' | 'monthly'
    },
    selectedStylistId: {
      key: 'stylistId',
      defaultValue: ''
    }
  })
  const { value: activeTab, setValue: setActiveTab } = queryStates.activeTab
  const { value: selectedStylistId, setValue: setSelectedStylistId } = queryStates.selectedStylistId

  const tabItems: TabItem[] = [
    { value: "daily", label: t("calendar.tabs.daily") },
    { value: "weekly", label: t("calendar.tabs.weekly") },
    { value: "monthly", label: t("calendar.tabs.monthly") }
  ]

  const { data: appointmentsData, isLoading: isLoadingAppointments } = useGetAppointments({
    range: activeTab as "daily" | "weekly" | "monthly",
    date: date ? formatLocalDate(date) : undefined,
    stylistId: selectedStylistId || undefined
  })

  const handleTabChange = (newTab: string) => {
    if (['daily', 'weekly', 'monthly'].includes(newTab)) {
      setActiveTab(newTab as 'daily' | 'weekly' | 'monthly')
    }
  }

  const handleStylistChange = (stylistId: string) => {
    setSelectedStylistId(stylistId)
  }

  const staffMembers: StaffMember[] = useMemo(() => {
    if (!stylists?.data) return []

    if (selectedStylistId) {
      const selectedStylist = stylists.data.find(stylist => stylist._id === selectedStylistId)
      return selectedStylist ? [{
        id: 0,
        name: selectedStylist.name,
        avatar: selectedStylist.image || "",
        title: selectedStylist.services[0]?.name || "Stylist"
      }] : []
    }

    return stylists.data.map((stylist, index) => ({
      id: index,
      name: stylist.name,
      avatar: stylist.image || "",
      title: stylist.services[0]?.name || "Stylist"
    }))
  }, [stylists, selectedStylistId])


  const stylistOptions = useMemo(() => {
    if (!stylists?.data) return []
    return [
      { value: "", label: t("calendar.form.allStylists") },
      ...stylists.data.map(stylist => ({
        value: stylist._id,
        label: stylist.name
      }))
    ]
  }, [stylists, t])

  const mappedServices = useMemo(
    () =>
      servicesData?.map(service => ({
        label: service.name,
        value: service._id,
        description: service.description || ""
      })) || [],
    [servicesData]
  )

  const mappedClients = useMemo(() => {
    const clientList = Array.isArray(clientsData_raw) ? clientsData_raw : (clientsData_raw as any)?.data || []
    return (
      clientList.map((client: any) => ({
        label: client.name,
        value: client.clientId || client._id,
        description: `Email: ${client.email} | Phone: ${client.phone}`
      })) || []
    )
  }, [clientsData_raw])


  // Transform API appointments with proper timezone handling
  const allAppointments: Appointment[] = useMemo(() => {
    if (!appointmentsData) return []

    const userTZ = user?.timezone || "UTC"

    return appointmentsData.map((appointment, index) => {
      let staffId: number
      if (selectedStylistId) {
        staffId = 0
      } else {
        staffId = staffMembers.findIndex(staff => staff.name === (appointment.stylist?.name || ""))
        staffId = staffId >= 0 ? staffId : 0
      }

      // Convert UTC time to user's timezone date
      const dateKey = utcToUserDate(appointment.start, userTZ)

      return {
        id: parseInt(appointment._id.slice(-6), 16),
        bookingId: appointment._id,
        staffId,
        date: new Date(appointment.start),
        dateKey, // This is now the date in user's timezone (YYYY-MM-DD)
        startTime: appointment.start,
        endTime: appointment.end,
        clientName: appointment.client?.name || "Unknown Client",
        service: appointment.service?.name || "Unknown Service",
        status: appointment.status,
        color: (["cyan", "orange", "teal", "pink"] as const)[index % 4],
        generatedBy: appointment.generatedBy,
        clientId: appointment.client?._id || (appointment.client as any)?.clientId,
        serviceId: appointment.service?._id,
        salonId: appointment.salonId || appointment.service?.salonId,
        realStylistId: appointment.stylist?._id,
        offerId: appointment.offer?._id || (appointment as any).offerId
      }
    })
  }, [appointmentsData, staffMembers, selectedStylistId, user?.timezone])

  useEffect(() => {
    if (!date) {
      setDate(new Date())
    }
  }, [date])

  // Filter appointments based on date range
  const filteredAppointments = useMemo(() => {
    if (!date) return []

    let start: Date, end: Date

    switch (activeTab) {
      case "daily":
        start = date
        end = date
        break
      case "weekly":
        start = startOfWeek(date, { weekStartsOn: 1 })
        end = endOfWeek(date, { weekStartsOn: 1 })
        break
      case "monthly":
        start = startOfMonth(date)
        end = endOfMonth(date)
        break
      default:
        start = date
        end = date
    }

    const startKey = formatLocalDate(start)
    const endKey = formatLocalDate(end)

    const filtered = allAppointments.filter(appointment => {
      const isInRange = appointment.dateKey >= startKey && appointment.dateKey <= endKey

      if (isInRange) {
        console.log('✓ Appointment matches:', {
          dateKey: appointment.dateKey,
          client: appointment.clientName,
          startKey,
          endKey
        })
      }

      return isInRange
    })

    return filtered
  }, [activeTab, date, allAppointments])

  // Group appointments by time slots
  const timeSlots = useMemo(() => {
    const slots: { [key: string]: Appointment[] } = {}
    const timeSlotLabels = ["06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"]

    timeSlotLabels.forEach(time => {
      slots[time] = []
    })

    filteredAppointments.forEach(appointment => {
      const userTimeZone = user?.timezone || "UTC"
      const roundedHour = getHourInTimeZone(appointment.startTime, userTimeZone)

      if (slots[roundedHour]) {
        slots[roundedHour].push(appointment)
      }
    })

    return slots
  }, [filteredAppointments, user?.timezone])

  return (
    <div className="mt-6">
      <CustomTabs
        items={tabItems}
        activeValue={activeTab}
        onTabChange={handleTabChange}
        rightContent={
          <div className="flex gap-3 items-center">
            <div className="min-w-[190px]">
              <label className="sr-only">Stylist</label>
              <Autocomplete
                options={stylistOptions}
                value={selectedStylistId}
                onChange={handleStylistChange}
                placeholder="All Stylists"
                searchPlaceholder="Search stylists..."
                emptyMessage="No stylists found."
                className="h-12"
              />
            </div>
            <div className="min-w-[220px] w-[220px]">
              <label className="sr-only">Date</label>
              <Popover open={datePickerOpen} onOpenChange={setDatePickerOpen}>
                <PopoverTrigger asChild>
                  <button
                    type="button"
                    className="h-12 w-full bg-white border border-gray-300 rounded-sm px-4 text-base flex items-center relative text-left"
                  >
                    <span className={date ? "text-gray-900" : "text-gray-400"}>
                      {date
                        ? date.toLocaleDateString(locale, {
                          day: '2-digit',
                          month: 'long',
                          year: 'numeric'
                        })
                        : t("calendar.form.datePlaceholder")}
                    </span>
                    <span className="absolute right-4 top-1/2 -translate-y-1/2">
                      <svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                        <rect x="3" y="4" width="18" height="18" rx="2" />
                        <path d="M16 2v4M8 2v4M3 10h18" />
                      </svg>
                    </span>
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0 z-100" align="start">
                  <Calendar
                    mode="single"
                    locale={calendarLocale}
                    selected={date}
                    onSelect={d => {
                      setDate(d)
                      setDatePickerOpen(false)
                    }}
                  />
                </PopoverContent>
              </Popover>
            </div>
          </div>
        }
      >
        <TabsContent value="daily" className="">
          <Card className="rounded-sm w-full min-w-0 overflow-hidden">
            <CardContent className="p-4 min-w-0 h-[600px]">
              {isLoadingStylists ? (
                <div className="flex items-center justify-center h-full">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue"></div>
                  <span className="ml-2 text-gray-600">{t("calendar.loading.staff")}</span>
                </div>
              ) : (
                <CalendarGrid
                  staffMembers={staffMembers}
                  timeSlots={timeSlots}
                  date={date!}
                  activeTab={activeTab}
                  allAppointments={allAppointments}
                  services={mappedServices}
                  clients={mappedClients}
                  onAppointmentUpdate={onAppointmentUpdate}
                />
              )}
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="weekly" className="">
          <Card className="rounded-sm w-full min-w-0 overflow-hidden">
            <CardContent className="p-4 min-w-0 h-[600px]">
              {isLoadingStylists ? (
                <div className="flex items-center justify-center h-full">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue"></div>
                  <span className="ml-2 text-gray-600">{t("calendar.loading.staff")}</span>
                </div>
              ) : (
                <CalendarGrid
                  staffMembers={staffMembers}
                  timeSlots={timeSlots}
                  date={date!}
                  activeTab={activeTab}
                  allAppointments={allAppointments}
                  services={mappedServices}
                  clients={mappedClients}
                  onAppointmentUpdate={onAppointmentUpdate}
                />
              )}
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="monthly" className="">
          <Card className="rounded-sm w-full min-w-0 overflow-hidden">
            <CardContent className="p-4 min-w-0 h-[600px]">
              {isLoadingStylists ? (
                <div className="flex items-center justify-center h-full">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue"></div>
                  <span className="ml-2 text-gray-600">{t("calendar.loading.staff")}</span>
                </div>
              ) : (
                <CalendarGrid
                  staffMembers={staffMembers}
                  timeSlots={timeSlots}
                  date={date!}
                  activeTab={activeTab}
                  allAppointments={allAppointments}
                  services={mappedServices}
                  clients={mappedClients}
                  onAppointmentUpdate={onAppointmentUpdate}
                />
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </CustomTabs>
    </div>
  )
}
