import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@workspace/ui/components/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@workspace/ui/components/form";
import {
  RadioGroup,
  RadioGroupItem,
} from "@workspace/ui/components/radio-group";
import { ScrollArea } from "@workspace/ui/components/scroll-area";
import {
  Sheet,
  SheetContent,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@workspace/ui/components/sheet";
import { Switch } from "@workspace/ui/components/switch";
import { DatePicker } from "@workspace/ui/composed/date-picker";
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { promoRuleTypes } from "./utils";

const ruleSchema = z
  .object({
    name: z.string().min(1),
    type: z.enum(["new_user", "inactive_user", "campaign"]),
    inactive_months: z.number().optional(),
    window_hours: z.number().optional(),
    priority: z.number().min(0),
    enabled: z.boolean(),
    start_time: z.number().optional(),
    end_time: z.number().optional(),
  })
  .superRefine((data, ctx) => {
    if (
      data.start_time !== undefined &&
      data.end_time !== undefined &&
      data.start_time >= data.end_time
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "End time must be later than start time",
        path: ["end_time"],
      });
    }
    if (
      data.type === "inactive_user" &&
      (!data.inactive_months || data.inactive_months <= 0)
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Inactive months must be greater than 0",
        path: ["inactive_months"],
      });
    }
    if (
      data.type === "new_user" &&
      (!data.window_hours || data.window_hours <= 0)
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Window hours must be greater than 0",
        path: ["window_hours"],
      });
    }
  });

type RuleFormValues = z.infer<typeof ruleSchema>;

interface RuleFormProps {
  initialValues?: API.PromoRule;
  loading?: boolean;
  onSubmit: (data: API.CreatePromoRuleRequest) => Promise<boolean> | boolean;
  title: string;
  trigger: string;
}

function toFormValues(rule?: API.PromoRule): RuleFormValues {
  return {
    name: rule?.name ?? "",
    type: rule?.type ?? "inactive_user",
    inactive_months: rule?.params?.inactive_months,
    window_hours: rule?.params?.window_hours,
    priority: rule?.priority ?? 0,
    enabled: rule?.enabled ?? false,
    start_time: rule?.start_time,
    end_time: rule?.end_time,
  };
}

function toRequest(values: RuleFormValues): API.CreatePromoRuleRequest {
  const params: API.PromoRuleParams =
    values.type === "inactive_user"
      ? { inactive_months: values.inactive_months }
      : values.type === "new_user"
        ? { window_hours: values.window_hours }
        : {};

  return {
    name: values.name.trim(),
    type: values.type,
    params,
    priority: values.priority,
    enabled: values.enabled,
    start_time: values.start_time || undefined,
    end_time: values.end_time || undefined,
  };
}

export default function RuleForm({
  initialValues,
  loading,
  onSubmit,
  title,
  trigger,
}: RuleFormProps) {
  const { t } = useTranslation("promo");
  const [open, setOpen] = useState(false);
  const form = useForm<RuleFormValues>({
    resolver: zodResolver(ruleSchema),
    defaultValues: toFormValues(initialValues),
  });
  const type = form.watch("type");

  useEffect(() => {
    form.reset(toFormValues(initialValues));
  }, [form, initialValues]);

  async function handleSubmit(values: RuleFormValues) {
    const success = await onSubmit(toRequest(values));
    if (success) setOpen(false);
  }

  return (
    <Sheet onOpenChange={setOpen} open={open}>
      <SheetTrigger asChild>
        <Button
          onClick={() => {
            form.reset(toFormValues(initialValues));
            setOpen(true);
          }}
          size="sm"
        >
          {trigger}
        </Button>
      </SheetTrigger>
      <SheetContent className="w-[520px] max-w-full md:max-w-screen-md">
        <SheetHeader>
          <SheetTitle>{title}</SheetTitle>
        </SheetHeader>
        <ScrollArea className="h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]">
          <Form {...form}>
            <form
              className="space-y-4 px-6 pt-4"
              id="promo-rule-form"
              onSubmit={form.handleSubmit(handleSubmit)}
            >
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("form.name", "Name")}</FormLabel>
                    <FormControl>
                      <EnhancedInput
                        onValueChange={(value) => field.onChange(value)}
                        placeholder={t("form.namePlaceholder", "Rule name")}
                        value={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("form.type", "Rule Type")}</FormLabel>
                    <FormControl>
                      <RadioGroup
                        className="grid gap-2 sm:grid-cols-3"
                        onValueChange={(value) =>
                          field.onChange(value as API.PromoRuleType)
                        }
                        value={field.value}
                      >
                        {promoRuleTypes.map((item) => (
                          <FormItem
                            className="flex items-center space-x-2 space-y-0"
                            key={item}
                          >
                            <FormControl>
                              <RadioGroupItem value={item} />
                            </FormControl>
                            <FormLabel className="font-normal">
                              {t(`types.${item}`, item)}
                            </FormLabel>
                          </FormItem>
                        ))}
                      </RadioGroup>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {type === "inactive_user" && (
                <FormField
                  control={form.control}
                  name="inactive_months"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t("form.inactiveMonths", "Inactive Months")}
                      </FormLabel>
                      <FormControl>
                        <EnhancedInput
                          min={1}
                          onValueChange={(value) => field.onChange(value)}
                          placeholder={t(
                            "form.inactiveMonthsPlaceholder",
                            "Months without purchase"
                          )}
                          type="number"
                          value={field.value}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
              {type === "new_user" && (
                <FormField
                  control={form.control}
                  name="window_hours"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t("form.windowHours", "Window Hours")}
                      </FormLabel>
                      <FormControl>
                        <EnhancedInput
                          min={1}
                          onValueChange={(value) => field.onChange(value)}
                          placeholder={t(
                            "form.windowHoursPlaceholder",
                            "Hours after registration"
                          )}
                          type="number"
                          value={field.value}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
              <FormField
                control={form.control}
                name="priority"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("priority", "Priority")}</FormLabel>
                    <FormControl>
                      <EnhancedInput
                        min={0}
                        onValueChange={(value) => field.onChange(value)}
                        placeholder="0"
                        type="number"
                        value={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="grid gap-4 sm:grid-cols-2">
                <FormField
                  control={form.control}
                  name="start_time"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("startTime", "Start Time")}</FormLabel>
                      <FormControl>
                        <DatePicker
                          onChange={(value) => field.onChange(value)}
                          placeholder={t("form.selectStartTime", "Select time")}
                          value={field.value}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="end_time"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("endTime", "End Time")}</FormLabel>
                      <FormControl>
                        <DatePicker
                          onChange={(value) => field.onChange(value)}
                          placeholder={t("form.selectEndTime", "Select time")}
                          value={field.value}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <FormField
                control={form.control}
                name="enabled"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-md border p-3">
                    <div>
                      <FormLabel>{t("enabled", "Enabled")}</FormLabel>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </ScrollArea>
        <SheetFooter>
          <Button disabled={loading} form="promo-rule-form" type="submit">
            {t("confirm", "Confirm")}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
