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 { ScrollArea } from "@workspace/ui/components/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@workspace/ui/components/select";
import {
  Sheet,
  SheetContent,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@workspace/ui/components/sheet";
import { Textarea } from "@workspace/ui/components/textarea";
import { DatePicker } from "@workspace/ui/composed/date-picker";
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
import { Icon } from "@workspace/ui/composed/icon";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";

const GRID_SIZE_OPTIONS = [8, 9] as const;

const getFormSchema = (t: (key: string, defaultValue: string) => string) =>
  z
    .object({
      title: z.string().min(1, t("form.titleRequired", "Title is required")),
      description: z.string().optional(),
      // DatePicker works in milliseconds; converted to Unix seconds on submit
      start_at: z
        .number()
        .min(1, t("form.startAtRequired", "Start time is required")),
      end_at: z
        .number()
        .min(1, t("form.endAtRequired", "End time is required")),
      grid_size: z.number(),
    })
    .superRefine((data, ctx) => {
      if (
        data.start_at > 0 &&
        data.end_at > 0 &&
        data.end_at <= data.start_at
      ) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: t(
            "form.endAtAfterStartAt",
            "End time must be later than start time"
          ),
          path: ["end_at"],
        });
      }
    });

type ActivityFormValues = z.infer<ReturnType<typeof getFormSchema>>;

interface ActivityFormProps {
  trigger: React.ReactNode;
  title: string;
  loading?: boolean;
  initialValues?: Partial<API.LotteryActivity>;
  onSubmit: (values: API.CreateLotteryActivityRequest) => Promise<boolean>;
}

function toFormValues(
  activity?: Partial<API.LotteryActivity>
): ActivityFormValues {
  return {
    title: activity?.title ?? "",
    description: activity?.description ?? "",
    start_at: activity?.start_at ? activity.start_at * 1000 : 0,
    end_at: activity?.end_at ? activity.end_at * 1000 : 0,
    grid_size: activity?.grid_size ?? GRID_SIZE_OPTIONS[0],
  };
}

export default function ActivityForm({
  trigger,
  title,
  loading,
  initialValues,
  onSubmit,
}: ActivityFormProps) {
  const { t } = useTranslation("lottery");
  const formSchema = getFormSchema(t);

  const [open, setOpen] = useState(false);
  const form = useForm<ActivityFormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: toFormValues(initialValues),
  });

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

  async function handleSubmit(values: ActivityFormValues) {
    const success = await onSubmit({
      title: values.title.trim(),
      description: values.description ?? "",
      start_at: Math.floor(values.start_at / 1000),
      end_at: Math.floor(values.end_at / 1000),
      grid_size: values.grid_size,
      eligibility: initialValues?.eligibility ?? {},
      chance_sources: initialValues?.chance_sources ?? [],
      unmet_action: "block",
    });
    if (success) {
      setOpen(false);
      form.reset(toFormValues(initialValues));
    }
  }

  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="lottery-activity-form"
              onSubmit={form.handleSubmit(handleSubmit)}
            >
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("form.title", "Title")}</FormLabel>
                    <FormControl>
                      <EnhancedInput
                        onValueChange={(value) => field.onChange(value)}
                        placeholder={t(
                          "form.titlePlaceholder",
                          "Activity title"
                        )}
                        value={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("form.description", "Description")}
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        onChange={(event) => field.onChange(event.target.value)}
                        placeholder={t(
                          "form.descriptionPlaceholder",
                          "Activity description (Markdown supported)"
                        )}
                        rows={5}
                        value={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="grid gap-4 sm:grid-cols-2">
                <FormField
                  control={form.control}
                  name="start_at"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("form.startAt", "Start Time")}</FormLabel>
                      <FormControl>
                        <DatePicker
                          onChange={(value) => field.onChange(value ?? 0)}
                          placeholder={t("form.selectStartAt", "Select time")}
                          value={field.value || undefined}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="end_at"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("form.endAt", "End Time")}</FormLabel>
                      <FormControl>
                        <DatePicker
                          onChange={(value) => field.onChange(value ?? 0)}
                          placeholder={t("form.selectEndAt", "Select time")}
                          value={field.value || undefined}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <FormField
                control={form.control}
                name="grid_size"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("form.gridSize", "Grid Size")}</FormLabel>
                    <Select
                      onValueChange={(value) => field.onChange(Number(value))}
                      value={String(field.value)}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue
                            placeholder={t(
                              "form.selectGridSize",
                              "Select grid size"
                            )}
                          />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {GRID_SIZE_OPTIONS.map((size) => (
                          <SelectItem key={size} value={String(size)}>
                            {size}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </ScrollArea>
        <SheetFooter className="flex-row justify-end gap-2 pt-3">
          <Button
            disabled={loading}
            onClick={() => {
              setOpen(false);
            }}
            variant="outline"
          >
            {t("form.cancel", "Cancel")}
          </Button>
          <Button disabled={loading} form="lottery-activity-form" type="submit">
            {loading && (
              <Icon className="mr-2 animate-spin" icon="mdi:loading" />
            )}{" "}
            {t("form.confirm", "Confirm")}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
