"use client"
import React, { useState } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useGetServices } from "@/lib/react-query/hooks/services"
import type { CreateStylistPayload, Stylist } from "@/types/stylists"
import { Badge } from "@/components/ui/badge"
import { X } from "lucide-react"
import { Clock } from "lucide-react"
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar"
import { Camera } from "lucide-react"
import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'
import { useTranslations } from "next-intl"

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"

const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

type Props = {
  initialValues?: Partial<Stylist>
  onSubmit: (payload: CreateStylistPayload & { imageFile?: File | null }) => Promise<void> | void
  submitLabel?: string
  isSubmitting?: boolean
  onCancel?: () => void
  onOpenWorkingHours?: () => void
  workingHours?: any[]
}

export function StaffForm({
  initialValues,
  onSubmit,
  submitLabel = "Save",
  isSubmitting = false,
  onCancel,
  onOpenWorkingHours,
  workingHours
}: Props) {
  const { data: services, isLoading: servicesLoading } = useGetServices()
  const [selectedImage, setSelectedImage] = useState<string | null>(null)
  const [imageFile, setImageFile] = useState<File | null>(null)
  const t = useTranslations()

  const stylistSchema = z.object({
    name: z.string().min(2, t("staff.validation.nameRequired")),
    email: z.string().optional().refine((val) => !val || emailRegex.test(val), {
      message: t("staff.validation.emailInvalid"),
    }),
    phone: z.string().optional().refine((val) => !val || val.length >= 8, {
      message: t("staff.validation.phoneInvalid"),
    }),
    role: z.string().optional(),
    countryCode: z.string().optional(),
    services: z.array(z.string()).optional()
  })

  type StaffFormValues = z.infer<typeof stylistSchema>

  const form = useForm<StaffFormValues>({
    resolver: zodResolver(stylistSchema),
    defaultValues: {
      name: initialValues?.name ?? "",
      email: initialValues?.email ?? "",
      phone: initialValues?.phone ? (initialValues?.phone.startsWith('+') ? initialValues.phone : (initialValues.countryCode ?? "") + initialValues.phone) : "",
      role: initialValues?.role ?? "",
      countryCode: initialValues?.countryCode ?? "+33",
      services: initialValues?.services?.map(s => (typeof s === "string" ? s : s._id)) ?? []
    }
  })

  // Reset form when initialValues change (for editing existing staff)
  React.useEffect(() => {
    if (initialValues) {
      form.reset({
        name: initialValues.name ?? "",
        email: initialValues.email ?? "",
        phone: initialValues.phone ? (initialValues.phone.startsWith('+') ? initialValues.phone : (initialValues.countryCode ?? "") + initialValues.phone) : "",
        role: initialValues.role ?? "",
        countryCode: initialValues.countryCode ?? "+33",
        services: initialValues.services?.map(s => (typeof s === "string" ? s : s._id)) ?? []
      })
    }
  }, [initialValues, form])

  // Helper function to transform working hours for API
  const transformWorkingHoursForAPI = (hours: any) => {
    // Normalize to object format first, then convert to array
    const normalizeWorkingHours = (hours: any) => {
      const dayMap: Record<string, any> = {}

      // Array format (legacy)
      if (Array.isArray(hours)) {
        hours.forEach(day => {
          if (day.enabled) {
            dayMap[day.day.toLowerCase()] = {
              day: day.day.toLowerCase(),
              enabled: true,
              slots: day.slots || []
            }
          }
        })
      }

      // Object format (new – should override)
      if (typeof hours === "object" && !Array.isArray(hours)) {
        Object.entries(hours).forEach(([day, schedule]: any) => {
          if (schedule.enabled) {
            dayMap[day.toLowerCase()] = {
              day: day.toLowerCase(),
              enabled: true,
              slots: schedule.timeSlots || []
            }
          }
        })
      }

      return Object.values(dayMap)
    }

    const normalized = normalizeWorkingHours(hours)
    return normalized
  }

  // Helper function to format working hours for display
  const formatWorkingHours = (hours: any) => {
    if (!hours || (Array.isArray(hours) && hours.length === 0) || (!Array.isArray(hours) && Object.keys(hours).length === 0)) return null

    const dayNames = {
      monday: t("staff.workingHours.monday"),
      tuesday: t("staff.workingHours.tuesday"),
      wednesday: t("staff.workingHours.wednesday"),
      thursday: t("staff.workingHours.thursday"),
      friday: t("staff.workingHours.friday"),
      saturday: t("staff.workingHours.saturday"),
      sunday: t("staff.workingHours.sunday")
    }

    const convertTo24Hour = (time: string) => {
      const [hour, minute] = time.split(':').map(Number)
      return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, '0')}`
    }

    // Normalize and deduplicate working hours by day (object format takes precedence)
    const normalizeWorkingHours = (hours: any) => {
      const dayMap: Record<string, any> = {}

      // Array format (legacy)
      if (Array.isArray(hours)) {
        hours.forEach(day => {
          if (day.enabled) {
            dayMap[day.day.toLowerCase()] = {
              day: day.day.toLowerCase(),
              enabled: true,
              slots: day.slots || []
            }
          }
        })
      }

      // Object format (new – should override)
      if (typeof hours === "object" && !Array.isArray(hours)) {
        Object.entries(hours).forEach(([day, schedule]: any) => {
          if (schedule.enabled) {
            dayMap[day.toLowerCase()] = {
              day: day.toLowerCase(),
              enabled: true,
              slots: schedule.timeSlots || []
            }
          }
        })
      }

      return Object.values(dayMap)
    }

    const enabledDays = normalizeWorkingHours(hours)

    if (enabledDays.length === 0) return t("staff.workingHours.noWorkingHours")

    return enabledDays
      .map(day => {
        const slots = day.slots.map((slot: any) => `${convertTo24Hour(slot.start)}-${convertTo24Hour(slot.end)}`).join(", ")
        return `${dayNames[day.day as keyof typeof dayNames]}: ${slots}`
      })
      .join(" | ")
  }

  // Handle image file selection
  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setImageFile(file)
      const reader = new FileReader()
      reader.onload = (e) => {
        setSelectedImage(e.target?.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  // Convert image file to base64
  const convertToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = () => {
        const base64 = reader.result as string
        // Remove the data:image/jpeg;base64, prefix
        const base64Data = base64.split(',')[1]
        resolve(base64Data)
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }

  async function handleSubmit(values: StaffFormValues) {
    const stylistData: CreateStylistPayload = {
      name: values.name,
      services: values.services,
      role: values.role,
      workingHours: workingHours ? transformWorkingHoursForAPI(workingHours) : [
        {
          day: "monday",
          enabled: true,
          slots: [{ start: "09:00", end: "18:00" }]
        }
      ]
    }

    // Only include email, phone, and countryCode if they have values
    stylistData.email = values.email || ""
    if (values.phone && values.phone.trim() !== "") {
      const countryCode = values.countryCode || ""
      let phone = values.phone
      if (countryCode && phone.startsWith(countryCode)) {
        phone = phone.slice(countryCode.length)
      }
      stylistData.phone = phone
    }
    if (values.countryCode && values.countryCode.trim() !== "") {
      stylistData.countryCode = values.countryCode
    }
    if (values.role && values.role.trim() !== "") {
      stylistData.role = values.role
    }

    // Pass the image file along with the stylist data
    await onSubmit({ ...stylistData, imageFile })
  }

  return (
    <div className="space-y-4">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
          {/* Profile Image Upload */}
          <div className="flex flex-col items-center space-y-4">
            <div className="relative">
              <Avatar className="w-24 h-24">
                <AvatarImage src={selectedImage || initialValues?.image || ""} alt={t("staff.form.profileAlt")} />
                <AvatarFallback className="text-2xl">
                  {form.watch("name")?.split(' ').map(n => n[0]).join('') || 'U'}
                </AvatarFallback>
              </Avatar>
              <label
                htmlFor="image-upload"
                className="absolute bottom-0 right-0 bg-primary-gradient text-white p-2 rounded-full cursor-pointer hover:opacity-90 transition-opacity"
              >
                <Camera className="w-4 h-4" />
                <input
                  id="image-upload"
                  type="file"
                  accept="image/*"
                  onChange={handleImageSelect}
                  className="hidden"
                />
              </label>
            </div>
            <p className="text-sm text-gray-500">{t("staff.form.uploadImage")}</p>
          </div>

          {/* First row: Name & Email (50/50) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="group">
              <FormField
                name="name"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="group-focus-within:text-primary-blue">{t("staff.form.name")}</FormLabel>
                    <FormControl>
                      <Input
                        className={fieldState.invalid ? errorInputClass : normalInputClass + " group w-full"}
                        placeholder={t("staff.form.name")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="group">
              <FormField
                name="email"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="group-focus-within:text-primary-blue">{t("staff.form.email")}</FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        className={fieldState.invalid ? errorInputClass : normalInputClass + " group w-full"}
                        placeholder={t("staff.form.email")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          {/* Second row: Phone & Role (50/50) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="group">
              <FormField
                name="phone"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="group-focus-within:text-primary-blue">{t("staff.form.phone")}</FormLabel>
                    <FormControl>
                      <PhoneInput
                        country={'fr'}
                        value={field.value}
                        onChange={(phone, data: any) => {
                          field.onChange(phone ? `+${phone}` : '');
                          if (data?.dialCode) {
                            form.setValue("countryCode", `+${data.dialCode}`);
                          }
                        }}
                        containerClass="!w-full"
                        inputClass={`${fieldState.invalid ? errorInputClass : normalInputClass} !w-full !pl-12 !h-12`}
                        buttonClass={`!bg-transparent !border-r-0 ${fieldState.invalid ? "!border-red-500" : "!border-gray-300"} !rounded-l-[var(--radius)] !h-12`}
                        dropdownClass="!bg-white !shadow-lg !rounded-md"
                        placeholder={t("staff.form.phone")}
                        disableDropdown={false}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="group">
              <FormField
                name="role"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="group-focus-within:text-primary-blue">{t("staff.form.role")}</FormLabel>
                    <FormControl>
                      <Select
                        value={field.value || ""}
                        onValueChange={field.onChange}
                      >
                        <SelectTrigger className={(fieldState.invalid ? errorInputClass : normalInputClass) + " group w-full"}>
                          <SelectValue placeholder={t("staff.form.role")} />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Intern">Intern</SelectItem>
                          <SelectItem value="Manager">Manager</SelectItem>
                          <SelectItem value="Hair Dresser">Hair Dresser</SelectItem>
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          {/* Third row: Services (Full width) */}
          <div className="group">
            <FormField
              name="services"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormItem>
                  <FormLabel className="group-focus-within:text-primary-blue">{t("staff.form.services")}</FormLabel>
                  <FormControl>
                    <Select
                      value=""
                      onValueChange={value => {
                        if (value && !(field.value || []).includes(value)) {
                          field.onChange([...(field.value || []), value])
                        }
                      }}
                      disabled={servicesLoading}
                    >
                      <SelectTrigger className={(fieldState.invalid ? errorInputClass : normalInputClass) + " group w-full py-5.5"}>
                        <SelectValue placeholder={t("staff.form.selectServices")} />
                      </SelectTrigger>
                      <SelectContent>
                        {services
                          ?.filter(service => !field.value?.includes(service._id))
                          .map(service => (
                            <SelectItem key={service._id} value={service._id}>
                              {service.name}
                            </SelectItem>
                          ))}
                        {services?.filter(service => !field.value?.includes(service._id)).length === 0 && (
                          <div className="px-2 py-1 text-sm text-gray-500">{t("staff.form.noServices")}</div>
                        )}
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* Selected Services Display - Below the grid */}
          <FormField
            name="services"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                {field.value && field.value.length > 0 ? (
                  <div className="group">
                    <FormLabel className="text-sm font-medium text-gray-700">Selected Services</FormLabel>
                    <div className="flex flex-wrap gap-2 mt-2">
                      {field.value.map((serviceId: string) => {
                        const service = services?.find(s => s._id === serviceId)
                        return (
                          <Badge
                            key={serviceId}
                            variant="secondary"
                            className="bg-blue-50 text-blue-700 border-blue-200 flex items-center gap-1"
                          >
                            {service?.name || serviceId}
                            <button
                              type="button"
                              onClick={() => {
                                const newValue = (field.value || []).filter((id: string) => id !== serviceId)
                                field.onChange(newValue)
                              }}
                              className="ml-1 hover:bg-blue-200 rounded-full p-0.5"
                            >
                              <X className="w-3 h-3" />
                            </button>
                          </Badge>
                        )
                      })}
                    </div>
                  </div>
                ) : (
                  <div className="group">
                    <FormLabel className="text-sm font-medium text-gray-700">{t("staff.form.servicesOptional")}</FormLabel>
                    <p className="text-sm text-gray-500 mt-1">{t("staff.form.noServicesSelected")}</p>
                  </div>
                )}
                <FormMessage />
              </FormItem>
            )}
          />

          {/* Working Hours Display */}
          {workingHours && workingHours.some(day => day.enabled) && (
            <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
              <div className="flex items-center gap-2 mb-2">
                <Clock className="w-4 h-4 text-blue-600" />
                <span className="text-sm font-medium text-blue-900">{t("staff.form.workingHours")}</span>
              </div>
              <p className="text-sm text-blue-800 leading-relaxed">{formatWorkingHours(workingHours)}</p>
            </div>
          )}

          {/* Set Working Hours below fields */}
          <div className="border border-dashed border-blue-950 rounded-md p-4 text-center mt-4">
            <button type="button" className="text-gradient-start text-sm font-normal hover:underline" onClick={onOpenWorkingHours}>
              {t("staff.form.setWorkingHours")}
            </button>
          </div>

          {/* Action buttons */}
          <div className="flex justify-end gap-2 pt-4">
            <Button type="button" variant="outline" onClick={onCancel} className="bg-transparent border-blue-950 text-blue-950 px-8">
              {t("common.cancel")}
            </Button>
            <Button type="submit" className="bg-primary-gradient text-white px-8" disabled={isSubmitting}>
              {isSubmitting ? t("common.saving") : submitLabel}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  )
}

export default StaffForm
