import React from "react"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button } from "@/components/ui/button"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { CalendarIcon } from "lucide-react"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { format } from "date-fns"
import { cn } from "@/lib/utils"
import { DialogFooter } from "@/components/ui/dialog"
import { useCreateOffer, useUpdateOffer } from "@/lib/react-query/hooks/offers"
import { OfferType, DiscountType, Offer, CreateOfferPayload } from "@/types/offers"
import { useTranslations, useLocale } from "next-intl"
import { enUS, fr } from "react-day-picker/locale"

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 createOfferFormSchema = (t: (key: string) => string) => z
  .object({
    offerTitle: z.string().min(1, t("marketing.form.validation.offerTitleRequired")),
    startDate: z.date().optional(),
    endDate: z.date().optional(),
    numberOfVisits: z.string().optional(),
    spendThreshold: z.string().optional(),
    description: z.string().min(1, t("marketing.form.validation.descriptionRequired")),
    message: z.string().min(1, t("marketing.form.validation.messageRequired")),
    discountValue: z.string().min(1, t("marketing.form.validation.discountValueRequired"))
  })
  .superRefine((data, ctx) => {
    return
  })

type OfferFormData = z.infer<ReturnType<typeof createOfferFormSchema>>

interface OfferFormProps {
  offerType: OfferType
  mode: "add" | "edit"
  initialData?: Offer
  onSuccess: () => void
  onCancel: () => void
}

export function OfferForm({ offerType, mode, initialData, onSuccess, onCancel }: OfferFormProps) {
  const createOfferMutation = useCreateOffer()
  const updateOfferMutation = useUpdateOffer()
  const t = useTranslations()
  const locale = useLocale()
  const dayPickerLocale = locale === "fr" ? fr : enUS

  const getSchema = () => {
    return createOfferFormSchema(t).superRefine((data, ctx) => {
      // Conditional validation based on offer type
      switch (offerType) {
        case OfferType.FESTIVE:
          if (!data.startDate) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: t("marketing.form.validation.startDateRequired"),
              path: ["startDate"]
            })
          }
          if (!data.endDate) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: t("marketing.form.validation.endDateRequired"),
              path: ["endDate"]
            })
          }
          break
        case OfferType.NTH_VISIT:
          if (!data.numberOfVisits || data.numberOfVisits.trim() === "") {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: t("marketing.form.validation.numberOfVisitsRequired"),
              path: ["numberOfVisits"]
            })
          }
          break
        case OfferType.SPEND_THRESHOLD:
          if (!data.spendThreshold || data.spendThreshold.trim() === "") {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: t("marketing.form.validation.spendThresholdRequired"),
              path: ["spendThreshold"]
            })
          }
          break
      }
    })
  }

  const getDefaultValues = (): OfferFormData => {
    if (mode === "edit" && initialData) {
      const baseValues = {
        offerTitle: initialData.title,
        description: initialData.description,
        message: initialData.message || "",
        discountValue: initialData.discountValue.toString()
      }

      switch (offerType) {
        case OfferType.FESTIVE:
          return {
            ...baseValues,
            startDate: initialData.startDate ? new Date(initialData.startDate) : undefined,
            endDate: initialData.endDate ? new Date(initialData.endDate) : undefined,
            numberOfVisits: undefined,
            spendThreshold: undefined
          }
        case OfferType.NTH_VISIT:
          return {
            ...baseValues,
            startDate: undefined,
            endDate: undefined,
            numberOfVisits: (initialData.visitCount || 0).toString(),
            spendThreshold: undefined
          }
        case OfferType.SPEND_THRESHOLD:
          return {
            ...baseValues,
            startDate: undefined,
            endDate: undefined,
            numberOfVisits: undefined,
            spendThreshold: (initialData.spendThreshold || 0).toString()
          }
        default:
          return {
            ...baseValues,
            startDate: undefined,
            endDate: undefined,
            numberOfVisits: undefined,
            spendThreshold: undefined
          }
      }
    }

    // Default values for add mode
    const baseValues = {
      offerTitle: "",
      description: "",
      message: "",
      discountValue: ""
    }

    switch (offerType) {
      case OfferType.FESTIVE:
        return {
          ...baseValues,
          startDate: undefined,
          endDate: undefined,
          numberOfVisits: undefined,
          spendThreshold: undefined
        }
      case OfferType.NTH_VISIT:
        return {
          ...baseValues,
          startDate: undefined,
          endDate: undefined,
          numberOfVisits: "",
          spendThreshold: undefined
        }
      case OfferType.SPEND_THRESHOLD:
        return {
          ...baseValues,
          startDate: undefined,
          endDate: undefined,
          numberOfVisits: undefined,
          spendThreshold: ""
        }
      default:
        return {
          ...baseValues,
          startDate: undefined,
          endDate: undefined,
          numberOfVisits: undefined,
          spendThreshold: undefined
        }
    }
  }

  const form = useForm({
    resolver: zodResolver(getSchema()),
    defaultValues: getDefaultValues()
  })

  function onSubmit(data: OfferFormData) {
    let payload: CreateOfferPayload

    switch (offerType) {
      case OfferType.FESTIVE:
        payload = {
          title: data.offerTitle,
          description: data.description,
          type: OfferType.FESTIVE,
          discountType: DiscountType.PERCENTAGE,
          discountValue: parseInt(data.discountValue),
          startDate: data.startDate ? format(data.startDate, "yyyy-MM-dd") : undefined,
          endDate: data.endDate ? format(data.endDate, "yyyy-MM-dd") : undefined,
          message: data.message,
          isActive: true
        }
        break
      case OfferType.NTH_VISIT:
        payload = {
          title: data.offerTitle,
          description: data.description,
          type: OfferType.NTH_VISIT,
          discountType: DiscountType.PERCENTAGE,
          discountValue: parseInt(data.discountValue),
          visitCount: data.numberOfVisits ? parseInt(data.numberOfVisits) : 0,
          message: data.message,
          isActive: true
        }
        break
      case OfferType.SPEND_THRESHOLD:
        payload = {
          title: data.offerTitle,
          description: data.description,
          type: OfferType.SPEND_THRESHOLD,
          discountType: DiscountType.PERCENTAGE,
          discountValue: parseInt(data.discountValue),
          spendThreshold: data.spendThreshold ? parseInt(data.spendThreshold) : 0,
          message: data.message,
          isActive: true
        }
        break
      default:
        // Fallback to festive type
        payload = {
          title: data.offerTitle,
          description: data.description,
          type: OfferType.FESTIVE,
          discountType: DiscountType.PERCENTAGE,
          discountValue: parseInt(data.discountValue),
          startDate: data.startDate ? format(data.startDate, "yyyy-MM-dd") : undefined,
          endDate: data.endDate ? format(data.endDate, "yyyy-MM-dd") : undefined,
          visitCount: 0,
          spendThreshold: 0,
          isActive: true
        }
    }

    if (mode === "edit" && initialData) {
      updateOfferMutation.mutate(
        { id: initialData._id, payload },
        {
          onSuccess: () => {
            onSuccess()
            form.reset()
          }
        }
      )
    } else {
      createOfferMutation.mutate(payload, {
        onSuccess: () => {
          onSuccess()
          form.reset()
        }
      })
    }
  }

  const isSubmitting = createOfferMutation.isPending || updateOfferMutation.isPending

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="overflow-y-auto px-1 max-h-[70vh]">
        <div className="space-y-4">
          <FormField
            name="offerTitle"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormItem>
                <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.offerTitle")}</FormLabel>
                <FormControl>
                  <Input className={fieldState.invalid ? errorInputClass : normalInputClass} placeholder={t("marketing.form.placeholders.offerTitle")} {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {offerType === OfferType.FESTIVE && (
            <div className="grid grid-cols-2 gap-4">
              <FormField
                name="startDate"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.startDate")}</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <FormControl>
                          <Button
                            variant={"outline"}
                            className={cn(
                              "w-full h-12 pl-3 text-left font-normal border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20 px-2 py-4 text-base bg-transparent hover:bg-transparent",
                              fieldState.invalid && "border-red-500"
                            )}
                          >
                            {field.value ? format(field.value, "PPP") : <span>{t("marketing.form.placeholders.startDate")}</span>}
                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                          </Button>
                        </FormControl>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0" align="start">
                        <Calendar locale={dayPickerLocale} mode="single" selected={field.value} onSelect={field.onChange} />
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                name="endDate"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.endDate")}</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <FormControl>
                          <Button
                            variant={"outline"}
                            className={cn(
                              "w-full h-12 pl-3 text-left font-normal border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20 px-2 py-4 text-base bg-transparent hover:bg-transparent",
                              fieldState.invalid && "border-red-500"
                            )}
                          >
                            {field.value ? format(field.value, "PPP") : <span>{t("marketing.form.placeholders.endDate")}</span>}
                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                          </Button>
                        </FormControl>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0" align="start">
                        <Calendar locale={dayPickerLocale} mode="single" selected={field.value} onSelect={field.onChange} initialFocus />
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          )}

          {offerType === OfferType.NTH_VISIT && (
            <FormField
              name="numberOfVisits"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormItem>
                  <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.numberOfVisits")}</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      className={fieldState.invalid ? errorInputClass : normalInputClass}
                      placeholder={t("marketing.form.placeholders.numberOfVisits")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}

          {offerType === OfferType.SPEND_THRESHOLD && (
            <FormField
              name="spendThreshold"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormItem>
                  <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.spendThreshold")}</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      className={fieldState.invalid ? errorInputClass : normalInputClass}
                      placeholder={t("marketing.form.placeholders.spendThreshold")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}
          <FormField
            name="description"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormItem>
                <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.description")}</FormLabel>
                <FormControl>
                  <Input className={fieldState.invalid ? errorInputClass : normalInputClass} placeholder={t("marketing.form.placeholders.description")} {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            name="message"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormItem>
                <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.message.label")}</FormLabel>
                <p className="text-sm text-gray-600 mb-2">
                  {t("marketing.form.labels.message.description", { client_name: "{client_name}" })}
                </p>
                <FormControl>
                  <Textarea 
                    className={fieldState.invalid ? "border-red-500" : "border-gray-300"} 
                    placeholder={t("marketing.form.placeholders.message")} 
                    rows={4}
                    {...field} 
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            name="discountValue"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormItem>
                <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f]">{t("marketing.form.labels.discountValue")}</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    min="0"
                    className={fieldState.invalid ? errorInputClass : normalInputClass}
                    placeholder={t("marketing.form.placeholders.discountValue")}
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <DialogFooter className="flex justify-end w-full">
            <div className="flex gap-2">
              <Button
                variant="outline"
                type="button"
                onClick={onCancel}
                className="flex-1 bg-transparent border-blue-950 text-blue-950 px-8"
              >
                {t("marketing.form.buttons.cancel")}
              </Button>
              <Button type="submit" className="flex-1 bg-primary-gradient text-white px-8" disabled={isSubmitting}>
                {isSubmitting ? (mode === "edit" ? t("marketing.form.buttons.updating") : t("marketing.form.buttons.creating")) : mode === "edit" ? t("marketing.form.buttons.updateOffer") : t("marketing.form.buttons.createOffer")}
              </Button>
            </div>
          </DialogFooter>
        </div>
      </form>
    </Form>
  )
}
