"use client"
import React 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 { Checkbox } from "@/components/ui/checkbox"
import { Textarea } from "@/components/ui/textarea"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import type { CreateReminderPayload, Reminder } from "@/types/reminders"
import { Badge } from "@/components/ui/badge"
import { X, MessageSquare } from "lucide-react"
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 createReminderSchema = (t: (key: string) => string, type?: string) => z.object({
  channels: z.array(z.string()).min(1, t("reminders.form.validation.channelsRequired")),
  message: z.string().min(1, t("reminders.form.validation.messageRequired")),
  isEnabled: z.boolean(),
  schedule: (type === "new_client" || type === "inactive_client")
    ? z.string().optional()
    : z.string().min(1, t("reminders.form.validation.scheduleRequired")),
  inactiveDays: z.union([z.string(), z.number()]).optional()
})

type ReminderFormValues = z.infer<ReturnType<typeof createReminderSchema>>

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

export function ReminderForm({ initialValues, onSubmit, submitLabel, isSubmitting = false, onCancel }: Props) {
  const t = useTranslations()

  const actualSubmitLabel = submitLabel || t("reminders.form.buttons.save")

  const reminderType = initialValues?.type
  const isNewClient = reminderType === "new_client"
  const isInactiveClient = reminderType === "inactive_client"
  const isAppointment = reminderType === "appointment"

  const reminderSchema = createReminderSchema(t, reminderType)

  const channelOptions = [
    // { value: "whatsapp", label: t("reminders.form.channels.options.whatsapp") },
    { value: "sms", label: t("reminders.form.channels.options.sms") },
    // { value: "instagram", label: t("reminders.form.channels.options.instagram") },
  ]

  const scheduleOptions = [
    { value: "30m_before", label: t("reminders.form.schedule.options.30m_before") },
    { value: "2h_before", label: t("reminders.form.schedule.options.2h_before") },
    { value: "24h_before", label: t("reminders.form.schedule.options.24h_before") },
    { value: "30m_after", label: t("reminders.form.schedule.options.30m_after") },
    { value: "2h_after", label: t("reminders.form.schedule.options.2h_after") },
    { value: "24h_after", label: t("reminders.form.schedule.options.24h_after") }
  ]

  const form = useForm<ReminderFormValues>({
    resolver: zodResolver(reminderSchema),
    defaultValues: {
      channels: initialValues?.channels?.length ? initialValues.channels : (channelOptions.length === 1 ? [channelOptions[0].value] : []),
      message: initialValues?.message || "",
      isEnabled: initialValues?.isEnabled ?? true,
      schedule: initialValues?.schedule || "",
      inactiveDays: initialValues?.inactiveDays !== undefined ? String(initialValues.inactiveDays) : ""
    }
  })

  async function handleSubmit(values: ReminderFormValues) {
    const reminderData: CreateReminderPayload = {
      channels: values.channels,
      message: values.message,
      isEnabled: values.isEnabled,
      ...(!isNewClient && !isInactiveClient && { schedule: values.schedule }),
      ...(isInactiveClient && values.inactiveDays !== undefined && String(values.inactiveDays).trim() && { inactiveDays: String(values.inactiveDays) })
    }

    await onSubmit(reminderData)
  }

  return (
    <div className="space-y-4">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
          {/* Schedule */}
          {!isNewClient && !isInactiveClient && (
            <div className="group">
              <FormField
                name="schedule"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f] group-focus-within:text-primary-blue">{t("reminders.form.schedule.label")}</FormLabel>
                    <FormControl>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <SelectTrigger className={fieldState.invalid ? errorInputClass : normalInputClass + " group w-full"}>
                          <SelectValue placeholder={t("reminders.form.schedule.placeholder")} />
                        </SelectTrigger>
                        <SelectContent>
                          {scheduleOptions.map(option => (
                            <SelectItem key={option.value} value={option.value}>
                              {option.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          )}

          {/* Channels */}
          <div className="group">
            <FormField
              name="channels"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormItem>
                  <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f] group-focus-within:text-primary-blue">{t("reminders.form.channels.label")}</FormLabel>
                  <FormControl>
                    <div className="space-y-2">
                      {channelOptions.length > 1 ? (
                        channelOptions.map(channel => (
                          <div key={channel.value} className="flex items-center space-x-2">
                            <Checkbox
                              id={channel.value}
                              checked={field.value?.includes(channel.value)}
                              onCheckedChange={checked => {
                                if (checked) {
                                  field.onChange([...(field.value || []), channel.value])
                                } else {
                                  field.onChange(field.value?.filter(v => v !== channel.value))
                                }
                              }}
                            />
                            <label
                              htmlFor={channel.value}
                              className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                            >
                              {channel.label}
                            </label>
                          </div>
                        ))
                      ) : (
                        <div className="pt-1">
                          <div className="flex items-center gap-3 p-3 rounded-xl border border-primary-blue/20 bg-primary-blue/5 w-fit shadow-sm">
                            <div className="bg-primary-gradient text-white p-2 rounded-lg">
                              <MessageSquare className="h-4 w-4" />
                            </div>
                            <div className="flex flex-col pr-4">
                              <span className="text-sm font-bold text-[#1a315f]">{channelOptions[0].label}</span>
                              <span className="text-[10px] text-[#1a315f]/60 font-medium uppercase tracking-tight">Active Channel</span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

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

          {/* Inactive Days (conditional) */}
          {isInactiveClient && (
            <div className="group">
              <FormField
                name="inactiveDays"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel className="text-[#1a315f] data-[error=true]:text-[#1a315f] group-focus-within:text-primary-blue">{t("reminders.form.inactiveDays.label")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        className={fieldState.invalid ? errorInputClass : normalInputClass + " group w-full"}
                        placeholder={t("reminders.form.inactiveDays.placeholder")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </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("reminders.form.buttons.cancel")}
            </Button>
            <Button type="submit" className="bg-primary-gradient text-white px-8" disabled={isSubmitting}>
              {isSubmitting ? t("reminders.form.buttons.saving") : actualSubmitLabel}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  )
}

export default ReminderForm
