"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Button } from "@/app/shadcn_components/ui/button";
import { useRouter } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/app/shadcn_components/ui/table";
import { useSession } from "next-auth/react";

async function deletePortfolio({
  userId,
  portfolioId,
}: {
  userId: bigint;
  portfolioId: string;
}) {
  const permissionsReponse = await fetch(
    `/api/portfolio/${portfolioId}/permissions`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userId: userId.toString(), action: "delete" }),
    },
  );

  const permissionsData = await permissionsReponse.json();
  if (!permissionsData.permitted) {
    throw new Error("User is not permitted to delete this portfolio");
  }

  const response = await fetch(`/api/portfolio/${portfolioId}`, {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  });

  if (!response.ok) {
    throw new Error("Failed to delete portfolio");
  }

  return await response.json();
}

export default function DangerZone({
  portfolioId,
  portfolioName,
}: {
  portfolioId: string;
  portfolioName: string;
}) {
  const session = useSession();
  const router = useRouter();

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [deleteConfirmationByName, setDeleteConfirmationByName] = useState("");

  const { mutate: mutateDelete } = useMutation(deletePortfolio, {
    onSuccess: () => {
      setIsDeleteModalOpen(false);
      router.push("/home");
    },
    onError: (error) => console.error("Delete failed", error),
  });

  if (session.status === "loading") return null;
  if (!session.data) return null;

  const userId = session.data.user.dbId;

  async function handleDeleteConfirmation() {
    if (deleteConfirmationByName !== portfolioName) return;
    mutateDelete({ userId, portfolioId });
  }

  return (
    <div className="rounded-md border border-red-500 mt-4">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead colSpan={2} className="text-lg text-brandblue">
              Danger Zone:
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow>
            <TableHead className="text-brandblue">
              Delete the Portfolio:
              <p className="text-xs text-gray-500">
                Permanently delete the portfolio and all property data assigned to this portfolio
              </p>
            </TableHead>
            <TableCell className="flex justify-end">
              <Button
                className="bg-red-700 w-42"
                onClick={() => {
                  setDeleteConfirmationByName("");
                  setIsDeleteModalOpen(true);
                }}
              >
                Delete Portfolio
              </Button>
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
      <Dialog open={isDeleteModalOpen} onOpenChange={setIsDeleteModalOpen}>
        <DialogContent>
          <DialogTitle>Are you sure?</DialogTitle>
          <p>
            To confirm, please type the name of the portfolio (
            <strong>{portfolioName}</strong>)
          </p>
          <input
            type="text"
            value={deleteConfirmationByName}
            onChange={(e) => setDeleteConfirmationByName(e.target.value)}
            placeholder="Type portfolio name"
          />
          <DialogFooter>
            <Button
              className="bg-green-600"
              onClick={() => setIsDeleteModalOpen(false)}
            >
              Cancel
            </Button>
            <Button
              className="bg-red-700"
              onClick={handleDeleteConfirmation}
              disabled={deleteConfirmationByName !== portfolioName}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
