"use client";

import { blockDevice } from "@/actions/omada-actions";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import type { Device } from "@prisma/client";
import { OctagonX } from "lucide-react";
import { useState } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { TextShimmer } from "./ui/text-shimmer";
import { Textarea } from "./ui/textarea";

const validationSchema = z.object({
  reasonForBlocking: z.string().min(5, { message: "Reason is required" }),
});

export default function BlockDeviceDialog({
  device,
  type,
  admin,
}: { device: Device; type: "block" | "unblock"; admin?: boolean }) {
  const [disabled, setDisabled] = useState(false);
  const [open, setOpen] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<z.infer<typeof validationSchema>>({
    resolver: zodResolver(validationSchema),
  });

  const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => {
    setDisabled(true);
    console.log(data);
    toast.promise(
      blockDevice({
        macAddress: device.mac,
        type: type,
        reason: data.reasonForBlocking,
        blockedBy: "ADMIN",
        // reason: data.reasonForBlocking,
      }),
      {
        loading: "Blocking...",
        success: () => {
          setDisabled(false);
          setOpen((prev) => !prev);
          return "Blocked!";
        },
        error: (error) => {
          setDisabled(false);
          return error || "Something went wrong";
        },
      },
    );
    setDisabled(false);
  };

  return (
    <div>
      {device.blocked ? (
        <Button
          onClick={() => {
            setDisabled(true);
            toast.promise(
              blockDevice({
                macAddress: device.mac,
                type: "unblock",
                reason: "",
              }),
              {
                loading: "unblockinig...",
                success: () => {
                  setDisabled(false);
                  return "Unblocked!";
                },
                error: () => {
                  setDisabled(false);
                  return "Something went wrong";
                },
              },
            );
          }}
        >

          {disabled ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"}
        </Button>
      ) : (
        <>
          {!admin ? (
            <Button
              variant={"destructive"}
              onClick={() => {
                setDisabled(true);
                toast.promise(
                  blockDevice({
                    macAddress: device.mac,
                    type: "block",
                    reason: "",
                    blockedBy: "PARENT",
                  }),
                  {
                    loading: "blocking...",
                    success: () => {
                      setDisabled(false);
                      return "blocked!";
                    },
                    error: () => {
                      setDisabled(false);
                      return "Something went wrong";
                    },
                  },
                );
              }}
            >
              <OctagonX />
              {disabled ? <TextShimmer>Blocking</TextShimmer> : "Block"}
            </Button>
          ) : (
            <Dialog open={open} onOpenChange={setOpen}>
              <DialogTrigger asChild>
                <Button disabled={disabled} variant="destructive">
                  <OctagonX />
                  Block
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                  <DialogTitle>
                    Please provide a reason for blocking this device.
                  </DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="grid gap-4 py-4">
                    <div className="flex flex-col items-start gap-1">
                      <Label htmlFor="reason" className="text-right">
                        Reason for blocking
                      </Label>
                      <Textarea
                        rows={10}
                        {...register("reasonForBlocking")}
                        id="reasonForBlocking"
                        className={cn(
                          "col-span-5",
                          errors.reasonForBlocking && "ring-2 ring-red-500",
                        )}
                      />
                      <span className="text-sm text-red-500">
                        {errors.reasonForBlocking?.message}
                      </span>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button
                      variant={"destructive"}
                      disabled={disabled}
                      type="submit"
                    >
                      Block
                    </Button>
                  </DialogFooter>
                </form>
              </DialogContent>
            </Dialog>
          )}
        </>
      )}
    </div>
  );
}
