"use client";
import { Button } from "@/components/ui/button";
import React, { useState } from "react";

import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/ui/toaster";

import { Loading } from "@/components/dashboard/loading";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
// import { trpc } from "@/lib/trpc/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { revalidate } from "./actions";
import { Modal, message } from "antd";
import { deleteStaff, frozenStaff, unfrozenStaff } from "@/lib/http/staff";

type Props = {
  api: {
    id: string;
    workspaceId: string;
    name: string;
    is_frozen: boolean; // 是否冻结
  };
};

const intent = "delete my api";

const { confirm } = Modal;

/**
 *  冻结员工
 * @param selectedRows
 */
const handleFrozen = async (id: number) => {


  const hide = message.loading('正在冻结员工');

  console.log("---冻结员工--->", id)
  try {
    await frozenStaff(Number(id));
    hide();
    message.success('冻结成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('冻结失败，请重试');
    return false;
  }
};


/**
 *  解冻员工
 * @param selectedRows
 */
const handleUnfrozen = async (id: number) => {


  const hide = message.loading('正在解冻员工');

  console.log("---解冻员工--->", id)
  try {
    await unfrozenStaff(Number(id));
    hide();
    message.success('解冻成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('解冻失败，请重试');
    return false;
  }
};

export const FrozenApi: React.FC<Props> = ({ api }) => {
  const [open, setOpen] = useState(false);
  const [isFrozenSubmitting, setIsFrozenSubmitting] = useState(false);
  const [isUnfrozenSubmitting, setIsUnfrozenSubmitting] = useState(false);
  const router = useRouter();

  const showFrozenConfirm = () => {
    confirm({
      title: '是否冻结员工?',
      content: '冻结于员工,请确认!',
      rootClassName: "bg-[#fff]",
      onOk() {
        const id = Number(api.id)
        setIsFrozenSubmitting(true)
        handleFrozen(id).then(() => {
          // window.location.href = `/manage`
          setIsFrozenSubmitting(false)
          // router.refresh()
          api.is_frozen = !api.is_frozen
        });
      },
      onCancel() {
        setIsFrozenSubmitting(false)
      },
    });
  };

  const showUnfrozenConfirm = () => {
    confirm({
      title: '是否解冻员工?',
      content: '解冻于员工,请确认!',
      rootClassName: "bg-[#fff]",
      onOk() {
        const id = Number(api.id)
        setIsUnfrozenSubmitting(true)
        handleUnfrozen(id).then(() => {
          // window.location.href = `/manage`
          setIsUnfrozenSubmitting(false)
          api.is_frozen = !api.is_frozen
        });
      },
      onCancel() {
        setIsUnfrozenSubmitting(false)
      },
    });
  };

  const formSchema = z.object({
    name: z.string().refine((v) => v === api.name, "Please confirm the API name"),
    intent: z.string().refine((v) => v === intent, "Please confirm your intent"),
  });

  const form = useForm<z.infer<typeof formSchema>>({
    // resolver: zodResolver(formSchema),
  });


  // const deleteApi = trpc.api.delete.useMutation({
  //   async onSuccess() {
  //     toast.message("API Deleted", {
  //       description: "Your API and all its keys has been deleted.",
  //     });

  //     await revalidate();

  //     router.push("/app/apis");
  //   },
  //   // onError(err) {
  //   //   console.error(err);
  //   //   toast.error(err.message);
  //   // },
  // });

  const isValid = form.watch("intent") === intent && form.watch("name") === api.name;

  async function onSubmit(_values: z.infer<typeof formSchema>) {
    // deleteApi.mutate({ apiId: api.id });
  }


  return (
    <>
      {
        api.is_frozen ? <Card className="relative border  mb-[1rem]">
          <CardHeader>
            <CardTitle>解冻员工</CardTitle>
            <CardDescription>
              该 员工客服 进行解冻，正常使用。
            </CardDescription>
          </CardHeader>

          <CardFooter className="z-10 justify-end">
            <Button type="button" onClick={() => {
              if (!api.id) {
                message.warning('id 不能为空');
                return;
              }
              showUnfrozenConfirm()
              // setOpen(!open)
            }} >

              {isUnfrozenSubmitting ? <Loading /> : "解冻"}
            </Button>
          </CardFooter>
        </Card>
          : <Card className="relative border  mb-[1rem]">
            <CardHeader>
              <CardTitle>冻结员工</CardTitle>
              <CardDescription>
                该 员工客服 进行冻结，暂停使用。
              </CardDescription>
            </CardHeader>

            <CardFooter className="z-10 justify-end">
              <Button type="button" onClick={() => {
                if (!api.id) {
                  message.warning('id 不能为空');
                  return;
                }
                showFrozenConfirm()
                // setOpen(!open)
              }} >

                {isFrozenSubmitting ? <Loading /> : "冻结"}
              </Button>
            </CardFooter>
          </Card>
      }

    </>
  );
};
