"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { EllipsisVerticalIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import { useRouter, usePathname } from "next/navigation";
import { formatNumber } from "@/app/utils";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/app/shadcn_components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader as ModalHeader,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/app/shadcn_components/ui/table";
import { Button } from "@/app/shadcn_components/ui/button";

type DeletionPreviewRow = { table: string; count: number };

async function fetchPlanDeletionPreview(planId: string): Promise<DeletionPreviewRow[]> {
  const res = await fetch(`/api/plan/${planId}/delete/preview`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
  });
  if (!res.ok) throw new Error("Failed to load deletion preview");
  return (await res.json()).preview;
}

async function confirmPlanDeletion(planId: string): Promise<void> {
  const res = await fetch(`/api/plan/${planId}/delete/confirm`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ confirm: true }),
  });
  if (!res.ok) throw new Error("Failed to delete plan");
}

export default function PlanCard({
  expectedEpcRating,
  currentEpcRating,
  createdAt,
  totalEstimatedCost,
  totalSapPoints,
  planName,
  planId,
  isDefault,
}: {
  expectedEpcRating: string;
  currentEpcRating: string;
  createdAt: Date;
  totalEstimatedCost: number;
  totalSapPoints: number;
  planName: string | null;
  planId: string;
  isDefault: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [setDefaultOpen, setSetDefaultOpen] = useState(false);
  const [settingDefault, setSettingDefault] = useState(false);
  const queryClient = useQueryClient();
  const router = useRouter();
  const pathname = usePathname();

  const {
    data: preview = [],
    isLoading,
    isError,
  } = useQuery({
    queryKey: ["planDeletionPreview", planId],
    queryFn: () => fetchPlanDeletionPreview(planId),
    enabled: open,
  });

  const deleteMutation = useMutation({
    mutationFn: () => confirmPlanDeletion(planId),
    onSuccess: () => {
      setOpen(false);
      queryClient.invalidateQueries({ queryKey: ["plans"] });
      router.refresh();
    },
  });

  async function handleSetDefault() {
    setSettingDefault(true);
    setSetDefaultOpen(false);
    try {
      await fetch(`/api/plan/${planId}/set-default`, { method: "POST" });
      router.refresh();
    } finally {
      setSettingDefault(false);
    }
  }

  const sapImprovement = Math.round((totalSapPoints + Number.EPSILON) * 100) / 100;

  return (
    <>
      <div className="bg-gray-50 rounded-2xl p-8 flex flex-col justify-between hover:shadow-md transition-shadow border border-gray-100 min-h-[220px]">
        <div>
          {/* Title row */}
          <div className="flex justify-between items-start mb-6">
            <h3 className="font-manrope font-extrabold text-2xl text-brandblue tracking-tight pr-4">
              {planName ?? "Unnamed Plan"}
            </h3>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button
                  type="button"
                  className="flex-shrink-0 rounded-lg p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-200 focus:outline-none transition"
                  aria-label="Plan options"
                >
                  <EllipsisVerticalIcon className="h-5 w-5" />
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  className="cursor-pointer"
                  onSelect={() => setSetDefaultOpen(true)}
                  disabled={settingDefault}
                >
                  {settingDefault ? "Setting…" : "Set as Default"}
                </DropdownMenuItem>
                <DropdownMenuItem
                  className="text-red-600 focus:text-red-600 focus:bg-red-50 cursor-pointer"
                  onSelect={() => setOpen(true)}
                >
                  Delete Plan
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          {/* Stats */}
          <div className="space-y-3">
            <div className="flex justify-between items-center text-sm">
              <span className="text-gray-400 font-medium">Expected EPC</span>
              <span className="font-bold text-brandblue">{expectedEpcRating}</span>
            </div>
            <div className="flex justify-between items-center text-sm">
              <span className="text-gray-400 font-medium">Investment</span>
              <span className="font-bold text-brandblue">£{formatNumber(totalEstimatedCost)}</span>
            </div>
            <div className="flex justify-between items-center text-sm">
              <span className="text-gray-400 font-medium">SAP Gain</span>
              <span className="font-bold text-brandblue">+{sapImprovement} pts</span>
            </div>
          </div>
        </div>

        {/* CTA */}
        <button
          type="button"
          onClick={() => router.push(`${pathname}/${planId}`)}
          className="mt-8 w-full text-brandmidblue font-manrope font-bold text-sm text-left flex items-center gap-2 hover:gap-3 transition-all group"
        >
          View Details
          <ArrowRightIcon className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
        </button>
      </div>

      {/* Set default confirmation modal */}
      <Dialog open={setDefaultOpen} onOpenChange={setSetDefaultOpen}>
        <DialogContent className="max-w-md">
          <ModalHeader>
            <DialogTitle className="font-manrope font-extrabold text-brandblue text-xl">
              Change default plan?
            </DialogTitle>
          </ModalHeader>
          <p className="text-sm text-gray-500 leading-relaxed">
            <span className="font-semibold text-brandblue">{planName ?? "This plan"}</span> will
            become the recommended strategy shown at the top of the page. You can change it again
            at any time.
          </p>
          <DialogFooter className="gap-2 pt-2">
            <Button variant="outline" onClick={() => setSetDefaultOpen(false)}>
              Cancel
            </Button>
            <Button
              className="bg-brandblue hover:bg-hoverblue text-white"
              onClick={handleSetDefault}
            >
              Yes, set as default
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete preview modal */}
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-lg">
          <ModalHeader>
            <DialogTitle className="text-red-600">Delete plan</DialogTitle>
          </ModalHeader>

          {isLoading ? (
            <p className="text-sm text-gray-500">Loading deletion preview…</p>
          ) : isError ? (
            <p className="text-sm text-red-600">Failed to load deletion preview</p>
          ) : (
            <div className="rounded-md border border-gray-200">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Table</TableHead>
                    <TableHead className="text-right">Rows deleted</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {preview.map((row) => (
                    <TableRow key={row.table}>
                      <TableCell className="font-mono text-sm">{row.table}</TableCell>
                      <TableCell className="text-right font-semibold">{row.count}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}

          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setOpen(false)} disabled={deleteMutation.isPending}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteMutation.mutate()}
              disabled={deleteMutation.isPending}
            >
              {deleteMutation.isPending ? "Deleting…" : "Delete plan"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
