import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState, type ReactNode } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { resourceApi } from "~/api/resource-api.service";
import Loader from "~/components/loader";
import { Button } from "~/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/ui/form";
import { Input } from "~/components/ui/input";
import { Switch } from "~/components/ui/switch";
import { Textarea } from "~/components/ui/textarea";
import { delay } from "~/features/delay";

// ✅ Zod schema
const resourceSchema = z.object({
  name: z.string().min(1, "Tên không được để trống"),
  description: z.string().min(1, "Mô tả không được để trống"),
  is_public: z.boolean().default(false),
  disabled: z.boolean().default(false),
});

export function ResourceItemModal({
  children,
  data,
  onSubmited,
}: {
  children: ReactNode;
  data: IResource;
  onSubmited?: () => void;
}) {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const form = useForm<Partial<IResource>>({
    resolver: zodResolver(resourceSchema) as any,
    defaultValues: {
      name: "",
      description: "",
      is_public: false,
      disabled: false,
    },
  });

  const onSubmit = async (values: Partial<IResource>) => {
    const { children, ...newData }: IResource = {
      ...data,
      ...values,
      disabled: !values.disabled,
    };

    setLoading(true);
    await delay(400);

    await resourceApi.update(newData);

    setLoading(false);

    onSubmited?.();

    setOpen(false);
  };

  useEffect(() => {
    form.reset({ ...data, disabled: !data.disabled });
  }, [data]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <DialogHeader>
              <DialogTitle>Chỉnh sửa</DialogTitle>
              <DialogDescription>
                Thực hiện các thay đổi resource ở đây. Nhấp SAVE để lưu thay đổi
              </DialogDescription>
            </DialogHeader>

            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tên</FormLabel>
                  <FormControl>
                    <Input placeholder="Tên chức năng..." {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mô tả</FormLabel>
                  <FormControl>
                    <Textarea placeholder="Mô tả chi tiết..." {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 🔘 Switch: Public */}
            <FormField
              control={form.control}
              name="is_public"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between">
                  <FormLabel>Công khai</FormLabel>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            {/* 🔘 Switch: Disabled */}
            <FormField
              control={form.control}
              name="disabled"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between">
                  <FormLabel>Hoạt động</FormLabel>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <DialogFooter>
              <DialogClose asChild>
                <Button disabled={loading} variant="outline" type="button">
                  Cancel
                </Button>
              </DialogClose>
              <Button disabled={loading} type="submit">
                Save
                {loading && <Loader color="white" />}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
