"use client"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { WorkingHoursForm } from "@/components/common/WorkingHoursForm"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Textarea } from "@/components/ui/textarea"
import { useForm, SubmitHandler } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState, useMemo } from "react"
import type { DaySchedule } from "@/components/common/WorkingHoursForm"
import type { CreateServicePayload } from "@/types/services"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { useGetStylists } from "@/lib/react-query/hooks/stylists"
import { useGetCategories } from "@/lib/react-query/hooks/services"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { X } from "lucide-react"

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"



type Props = {
  initialValues?: Partial<CreateServicePayload>
  onSubmit: (payload: CreateServicePayload) => Promise<void> | void
  submitLabel?: string
  isSubmitting?: boolean
}

export function ServiceForm({ initialValues, onSubmit, submitLabel = "Save", isSubmitting = false }: Props) {
  const t = useTranslations()

  const serviceSchema = useMemo(() => z.object({
    name: z.string().min(2, t("validation.serviceNameRequired")),
    description: z.string().optional(),
    basePrice: z.coerce.number().min(0, t("validation.priceNonNegative")),
    surchargePricePercentage: z.coerce.number().min(0, t("validation.surchargeNonNegative")).optional(),
    duration: z.coerce.number().min(0, t("validation.durationNonNegative")),
    stylistIds: z.array(z.string()).optional(),
    status: z.enum(["active", "inactive"]).optional()
  }), [t])

  type ServiceFormValues = z.infer<typeof serviceSchema>

  // const { data: stylists } = useGetStylists("active")
  const { data: stylists } = useGetStylists("all")
  const { data: categories } = useGetCategories()
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>(initialValues?.categoryId || "")

  const defaultSchedule = useMemo(
    () => ({
      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 [availability, setAvailability] = useState<Record<string, DaySchedule>>(
    // If initialValues includes availability in API format, convert to WorkingHoursForm shape
    () => {
      if (!initialValues || !initialValues.availability) return defaultSchedule
      const map: Record<string, DaySchedule> = { ...defaultSchedule }
      initialValues.availability.forEach(d => {
        const key = (d.day || "").toLowerCase()
        map[key] = { enabled: d.enabled, timeSlots: d.slots }
      })
      return map
    }
  )

  const [surchargeHours, setSurchargeHours] = useState<Record<string, DaySchedule>>(() => {
    if (!initialValues || !initialValues.surchargeHours) return defaultSchedule
    const map: Record<string, DaySchedule> = { ...defaultSchedule }
    initialValues.surchargeHours.forEach(d => {
      const key = (d.day || "").toLowerCase()
      map[key] = { enabled: d.enabled, timeSlots: d.slots }
    })
    return map
  })
  const router = useRouter()

  const form = useForm<any>({
    resolver: zodResolver(serviceSchema) as any,
    defaultValues: {
      name: initialValues?.name ?? "",
      description: initialValues?.description ?? "",
      basePrice: initialValues?.basePrice ?? undefined,
      surchargePricePercentage: initialValues?.surchargePricePercentage ?? undefined,
      duration: initialValues?.duration ?? undefined,
      stylistIds: initialValues?.stylistIds ?? [],
      status: (initialValues?.status as "active" | "inactive") ?? "active"
    }
  })

  const handleSubmit = async (values: ServiceFormValues) => {
    const transformedAvailability = Object.entries(availability).map(([day, schedule]) => ({
      day: day.toLowerCase(),
      enabled: schedule.enabled,
      slots: schedule.timeSlots
    }))

    const transformedSurchargeHours = Object.entries(surchargeHours).map(([day, schedule]) => ({
      day: day.toLowerCase(),
      enabled: schedule.enabled,
      slots: schedule.timeSlots
    }))

    // Find selected category name
    const selectedCategory = categories?.find(cat => cat._id === selectedCategoryId)

    const payload: CreateServicePayload = {
      name: values.name,
      basePrice: values.basePrice,
      duration: values.duration,
      surchargeHours: transformedSurchargeHours
    }

    // Include category and categoryId if selected
    if (selectedCategoryId && selectedCategory) {
      payload.category = selectedCategory.name
      payload.categoryId = selectedCategoryId
    }

    // Only include surchargePricePercentage if provided
    if (values.surchargePricePercentage !== undefined) {
      payload.surchargePricePercentage = values.surchargePricePercentage
    }

    // Only include description if provided
    if (values.description && values.description.trim() !== "") {
      payload.description = values.description
    }

    if (values.stylistIds && values.stylistIds.length > 0) {
      payload.stylistIds = values.stylistIds
    }

    if (values.status) {
      payload.status = values.status
    }

    await onSubmit(payload)
  }

  return (
    <div>
      <Card className="w-full mb-8 bg-white rounded-lg shadow-sm gap-2">
        <CardHeader>
          <CardTitle className="text-xl font-semibold">{initialValues ? t("services.form.editTitle") : t("services.form.addTitle")}</CardTitle>
        </CardHeader>
        <CardContent className="px-6 pb-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(handleSubmit)}>
              {/* Row 1: Service Name, Base Price, Surcharge */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="md:col-span-1">
                  <FormField
                    name="name"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <FormItem>
                        <FormLabel>{t("services.form.serviceNameLabel")}</FormLabel>
                        <FormControl>
                          <Input
                            className={fieldState.invalid ? errorInputClass : normalInputClass + " w-full"}
                            placeholder={t("services.form.serviceNamePlaceholder")}
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="md:col-span-1">
                  <FormField
                    name="basePrice"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <FormItem>
                        <FormLabel>{t("services.form.basePriceLabel")}</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            min="0"
                            className={fieldState.invalid ? errorInputClass : normalInputClass + " w-full"}
                            placeholder={t("services.form.basePricePlaceholder")}
                            value={field.value ?? ""}
                            onChange={e => field.onChange(e.target.value)}
                            step="any"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="md:col-span-1">
                  <FormField
                    name="surchargePricePercentage"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <FormItem>
                        <FormLabel>{t("services.form.surchargeLabel")}</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            min="0"
                            className={fieldState.invalid ? errorInputClass : normalInputClass + " w-full"}
                            placeholder={t("services.form.surchargePlaceholder")}
                            value={field.value ?? ""}
                            onChange={e => field.onChange(e.target.value)}
                            step="any"
                          />
                        </FormControl>
                        <div className="text-[10px] text-muted-foreground mt-1">
                          {t("services.form.surchargeHelp")}
                        </div>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>

              {/* Row 2: Category, Duration, Assign Stylists */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6">
                <div className="md:col-span-1">
                  <div className="space-y-2">
                    <label className="text-sm font-medium">{t("services.form.categoryLabel")}</label>
                    <Select
                      value={selectedCategoryId}
                      onValueChange={setSelectedCategoryId}
                    >
                      <SelectTrigger className={normalInputClass + " w-full"}>
                        <SelectValue placeholder={t("services.form.categoryPlaceholder")} />
                      </SelectTrigger>
                      <SelectContent>
                        {categories && categories.length > 0 ? (
                          categories.map((category) => (
                            <SelectItem key={category._id} value={category._id}>
                              {category.name}
                            </SelectItem>
                          ))
                        ) : (
                          <div className="py-3 text-center text-sm text-gray-500">{t("services.form.noCategoriesFound") || "No category added"}</div>
                        )}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="md:col-span-1">
                  <FormField
                    name="duration"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <FormItem>
                        <FormLabel>{t("services.form.durationLabel")}</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            min="0"
                            className={fieldState.invalid ? errorInputClass : normalInputClass + " w-full"}
                            placeholder={t("services.form.durationPlaceholder")}
                            value={field.value ?? ""}
                            onChange={e => field.onChange(e.target.value)}
                            step="any"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="md:col-span-1">
                  <FormField
                    name="stylistIds"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Assign Stylists</FormLabel>
                        <FormControl>
                          <Select
                            onValueChange={(value) => {
                              const current = field.value || []
                              if (!current.includes(value)) {
                                field.onChange([...current, value])
                              }
                            }}
                          >
                            <SelectTrigger className={normalInputClass + " w-full"}>
                              <SelectValue placeholder="Select stylists" />
                            </SelectTrigger>
                            <SelectContent>
                              {stylists?.data?.map((stylist) => (
                                <SelectItem key={stylist._id} value={stylist._id}>
                                  {stylist.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>

              {/* Selected Stylists Badges */}
              <FormField
                name="stylistIds"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    {field.value && field.value.length > 0 && (
                      <div className="flex flex-wrap gap-2 mt-3">
                        {field.value.map((stylistId: string) => {
                          const stylist = stylists?.data?.find(s => s._id === stylistId)
                          return (
                            <Badge key={stylistId} variant="secondary" className="px-3 py-1 flex items-center gap-2">
                              {stylist?.name || stylistId}
                              <button
                                type="button"
                                onClick={() => {
                                  const current = field.value || []
                                  field.onChange(current.filter((id: string) => id !== stylistId))
                                }}
                                className="hover:text-red-500"
                              >
                                <X className="h-3 w-3" />
                              </button>
                            </Badge>
                          )
                        })}
                      </div>
                    )}
                  </FormItem>
                )}
              />

              {/* Status Selection - Only shown during edit */}
              {initialValues && (
                <div className="mt-6">
                  <FormField
                    name="status"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t("services.form.statusLabel")}</FormLabel>
                        <Select
                          onValueChange={field.onChange}
                          defaultValue={field.value}
                          value={field.value}
                        >
                          <FormControl>
                            <SelectTrigger className={normalInputClass}>
                              <SelectValue placeholder={t("services.form.statusPlaceholder")} />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="active">{t("services.status.active")}</SelectItem>
                            <SelectItem value="inactive">{t("services.status.inactive")}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              )}

              {/* Description in its own full-width row */}
              <div className="mt-6">
                <FormField
                  name="description"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormItem>
                      <FormLabel>{t("services.form.descriptionLabel")}</FormLabel>
                      <FormControl>
                        <Textarea
                          className={fieldState.invalid ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200" : "border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20"}
                          placeholder={t("services.form.descriptionPlaceholder")}
                          rows={4}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Availability and Surcharge Hours in 2-column layout */}
              {/* Availability and Surcharge Hours */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
                {/* <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-900">{t("services.form.availabilityTitle")}</h3>
                  <WorkingHoursForm value={availability} onChange={setAvailability} />
                </div> */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-900">{t("services.form.surchargeHoursTitle")}</h3>
                  <WorkingHoursForm value={surchargeHours} onChange={setSurchargeHours} />
                </div>
              </div>
            </form>
          </Form>
        </CardContent>
      </Card>

      {/* Action buttons at the bottom */}
      <div className="flex justify-center gap-4 mt-4">
        <Button
          type="submit"
          className="px-8 bg-primary-gradient text-white"
          disabled={isSubmitting}
          onClick={form.handleSubmit(handleSubmit as any)}
        >
          {isSubmitting ? t("services.form.savingButton") : submitLabel}
        </Button>
      </div>
    </div>
  )
}

export default ServiceForm
