"use client";

import * as React from "react";
import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { saveCategoryAction } from "@/lib/actions/admin-services";
import { adminTexts } from "@/lib/i18n/admin";
import { adminServicesTexts as t } from "@/lib/i18n/admin-services";
import {
  PLATFORM_OPTIONS,
  type AdminActionState,
  type CategoryFormValues,
} from "./types";

const d = t.dialog;

type SaveState = AdminActionState<{ id: string }>;

export function CategoryDialog({
  title,
  initial,
  closeHref,
}: {
  title: string;
  initial: CategoryFormValues;
  closeHref: string;
}) {
  const router = useRouter();
  const [values, setValues] = React.useState<CategoryFormValues>(initial);
  const [state, formAction, pending] = useActionState<SaveState, FormData>(
    saveCategoryAction,
    null,
  );

  const close = React.useCallback(() => {
    router.push(closeHref, { scroll: false });
  }, [closeHref, router]);

  React.useEffect(() => {
    if (!state) return;
    if (state.ok) {
      toast.success(d.savedCategory);
      router.push(closeHref, { scroll: false });
      router.refresh();
    } else {
      toast.error(state.error);
    }
  }, [state, closeHref, router]);

  const errors = state && state.ok === false ? (state.fieldErrors ?? {}) : {};

  return (
    <Dialog open onOpenChange={(next) => (next ? null : close())}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="text-base">{title}</DialogTitle>
        </DialogHeader>

        <form action={formAction} className="space-y-3">
          <input type="hidden" name="id" value={values.id} />

          <div className="space-y-1.5">
            <Label htmlFor="cat-name" className="text-xs font-medium">
              {d.categoryName}
            </Label>
            <Input
              id="cat-name"
              name="name"
              required
              maxLength={160}
              value={values.name}
              onChange={(e) => setValues((p) => ({ ...p, name: e.target.value }))}
              className="h-8 text-sm"
            />
            {errors.name ? (
              <p className="text-[11px] font-medium text-rose-600 dark:text-rose-400">
                {errors.name}
              </p>
            ) : null}
          </div>

          <div className="grid gap-3 sm:grid-cols-2">
            <div className="space-y-1.5">
              <Label htmlFor="cat-platform" className="text-xs font-medium">
                {d.platform}
              </Label>
              <NativeSelect
                id="cat-platform"
                name="platform"
                className="w-full"
                value={values.platform}
                onChange={(e) => setValues((p) => ({ ...p, platform: e.target.value }))}
              >
                {PLATFORM_OPTIONS.map((o) => (
                  <NativeSelectOption key={o.value} value={o.value}>
                    {o.label}
                  </NativeSelectOption>
                ))}
              </NativeSelect>
            </div>

            <div className="space-y-1.5">
              <Label htmlFor="cat-position" className="text-xs font-medium">
                {d.position}
              </Label>
              <Input
                id="cat-position"
                name="position"
                type="number"
                min={0}
                value={values.position}
                onChange={(e) => setValues((p) => ({ ...p, position: e.target.value }))}
                className="h-8 font-mono text-sm"
              />
              {errors.position ? (
                <p className="text-[11px] font-medium text-rose-600 dark:text-rose-400">
                  {errors.position}
                </p>
              ) : null}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Checkbox
              id="cat-active"
              checked={values.active}
              onCheckedChange={(v) => setValues((p) => ({ ...p, active: v === true }))}
            />
            <input type="hidden" name="active" value={values.active ? "1" : "0"} />
            <Label htmlFor="cat-active" className="cursor-pointer text-xs font-medium">
              {d.active}
            </Label>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" size="lg" onClick={close}>
              {adminTexts.common.cancel}
            </Button>
            <Button type="submit" size="lg" disabled={pending}>
              {pending ? d.saving : values.id ? d.saveCategory : d.createCategory}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default CategoryDialog;
