import type { GetStaticProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import type { UsersId } from "~/schemas/public/Users";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import { Button } from "~/components/ui/button";
import { FormNewServizio, type FormValues } from "~/forms/FormNewServizio";
import { type Servizio } from "~/schemas/public/Servizio";
import { TabServizio } from "~/components/tables/servizio-table";
import { api } from "~/utils/api";
import toast from "react-hot-toast";
import { zUserId } from "~/server/utils/zod_types";
import { useState } from "react";

type ServizioUserProps = {
  userId: UsersId;
};
const ServizioUser: NextPageWithLayout<ServizioUserProps> = ({
  userId,
}: ServizioUserProps) => {
  const [open, setOpen] = useState(false);
  const [editData, setEditData] = useState<Servizio | undefined>(undefined);
  return (
    <div className="mx-auto max-w-7xl grow space-y-4">
      <div className="flex justify-between">
        <h3 className="text-2xl font-bold">Servizi Utente</h3>
        <NewServizioModal
          userId={userId}
          editData={editData}
          setEditData={setEditData}
          open={open}
          setOpen={setOpen}
        />
      </div>
      <TabServizio
        userId={userId}
        setEditData={setEditData}
        setOpen={setOpen}
      />
    </div>
  );
};
export default ServizioUser;

export const getStaticProps: GetStaticProps = (context) => {
  const userId = context.params?.userId;
  if (typeof userId !== "string") {
    return {
      notFound: true,
    };
  }

  const parsed = zUserId.safeParse(userId);

  if (!parsed.success) {
    {
      return {
        notFound: true,
      };
    }
  }

  return {
    props: {
      userId: parsed.data,
    },
  };
};

export const getStaticPaths = () => {
  return { paths: [], fallback: "blocking" };
};

ServizioUser.getLayout = function getLayout(page) {
  return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};

const NewServizioModal = ({
  userId,
  editData,

  setEditData,
  open,
  setOpen,
}: {
  userId: UsersId;
  editData: Servizio | undefined;
  setEditData: (data: Servizio | undefined) => void;
  open: boolean;
  setOpen: (open: boolean) => void;
}) => {
  const utils = api.useUtils();

  const { mutate: add } = api.servizio.addServizio.useMutation({
    onSuccess: async () => {
      toast.success("Servizio creato con successo");
      await utils.servizio.getUserServizi.invalidate();
      setEditData(undefined);
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const { mutate: update } = api.servizio.updateServizio.useMutation({
    onSuccess: async () => {
      toast.success("Servizio modificato con successo");
      await utils.servizio.getUserServizi.invalidate();
      setEditData(undefined);
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });
  function onSubmit(fields: FormValues) {
    if (editData) {
      update({
        servizioId: editData.servizio_id,
        data: {
          ...fields,
        },
      });
    } else {
      add({ data: { ...fields, user_id: userId } });
    }
  }
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          variant="outline"
          onClick={() => {
            setEditData(undefined);
            setOpen(true);
          }}
        >
          Nuovo Servizio
        </Button>
      </DialogTrigger>
      <DialogContent className="max-h-[80%] max-w-5xl overflow-auto p-4">
        <DialogHeader>
          <DialogTitle>Creazione Servizio</DialogTitle>
          <DialogDescription className="sr-only">desc</DialogDescription>
        </DialogHeader>
        <div className="overflow-y-auto">
          <FormNewServizio
            initialData={editData}
            onSubmit={onSubmit}
            isLimited={false}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};
