"use client";

import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useRouter, usePathname } from "next/navigation";
import {
  ArrowRightIcon,
  EllipsisVerticalIcon,
} from "@heroicons/react/24/outline";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/app/shadcn_components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  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";
import { formatNumber } from "@/app/utils";

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");
}

function getEpcHex(letter: string | null | undefined): string {
  switch (letter?.toUpperCase()) {
    case "A":
      return "#117d58";
    case "B":
      return "#2da55c";
    case "C":
      return "#8dbd40";
    case "D":
      return "#f7cd14";
    case "E":
      return "#f3a96a";
    case "F":
      return "#ef8026";
    case "G":
      return "#e41e3b";
    default:
      return "#9ca3af";
  }
}

function epcToPosition(rating: string): number {
  const map: Record<string, number> = {
    G: 0,
    F: 1 / 6,
    E: 2 / 6,
    D: 3 / 6,
    C: 4 / 6,
    B: 5 / 6,
    A: 1,
  };
  return map[rating?.toUpperCase()] ?? 0;
}

export default function PlanHeroCard({
  planId,
  planName,
  currentEpcRating,
  expectedEpcRating,
  totalEstimatedCost,
  totalSapPoints,
  co2Savings,
  energyBillSavings,
  valuationIncreaseLowerBound,
  valuationIncreaseUpperBound,
  createdAt,
}: {
  planId: string;
  planName: string | null;
  currentEpcRating: string;
  expectedEpcRating: string;
  totalEstimatedCost: number;
  totalSapPoints: number;
  co2Savings: number | null;
  energyBillSavings: number | null;
  valuationIncreaseLowerBound: number | null;
  valuationIncreaseUpperBound: number | null;
  createdAt: Date;
}) {
  const [deleteOpen, setDeleteOpen] = useState(false);
  const router = useRouter();
  const pathname = usePathname();

  const sapImprovement =
    Math.round((totalSapPoints + Number.EPSILON) * 100) / 100;
  const createdDate = new Date(createdAt).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });

  const currentHex = getEpcHex(currentEpcRating);
  const expectedHex = getEpcHex(expectedEpcRating);
  const currentPos = epcToPosition(currentEpcRating);
  const expectedPos = epcToPosition(expectedEpcRating);

  const carsEquivalent =
    co2Savings != null ? Math.round(co2Savings / 1.47) : null;

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

  const deleteMutation = useMutation({
    mutationFn: () => confirmPlanDeletion(planId),
    onSuccess: () => {
      setDeleteOpen(false);
      router.refresh();
    },
  });

  return (
    <>
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* ── Featured hero card ─────────────────────────────── */}
        <div className="lg:col-span-8 bg-white rounded-2xl shadow-sm border border-gray-100 p-8 flex flex-col md:flex-row gap-8">
          {/* Left: content */}
          <div className="flex-1 flex flex-col gap-7">
            {/* Header */}
            <div className="flex items-start justify-between gap-4">
              <div>
                <span className="inline-flex items-center gap-1.5 bg-brandblue text-brandgold px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider mb-3">
                  <svg
                    className="w-2.5 h-2.5"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                  >
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                  </svg>
                  Recommended Strategy
                </span>
                <h2 className="font-manrope font-extrabold text-3xl text-brandblue tracking-tight">
                  {planName ?? "Unnamed Plan"}
                </h2>
                <p className="text-sm text-gray-400 font-medium mt-1">
                  Created: {createdDate}
                </p>
              </div>

              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <button
                    type="button"
                    className="rounded-lg p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 focus:outline-none transition"
                    aria-label="Plan options"
                  >
                    <EllipsisVerticalIcon className="h-5 w-5" />
                  </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem
                    className="text-red-600 focus:text-red-600 focus:bg-red-50 cursor-pointer"
                    onSelect={() => setDeleteOpen(true)}
                  >
                    Delete Plan
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>

            {/* EPC progress */}
            <div className="space-y-4">
              <div className="flex justify-between text-[10px] font-bold uppercase tracking-widest text-gray-400">
                <span>Current Rating: {currentEpcRating}</span>
                <span>Target Rating: {expectedEpcRating}</span>
              </div>

              {/* Bar + pin */}
              <div className="relative py-2.5">
                <div className="relative h-3 w-full bg-gray-100 rounded-full">
                  <div
                    className="absolute inset-y-0 left-0 rounded-full"
                    style={{
                      width: `${expectedPos * 100}%`,
                      background: `linear-gradient(to right, ${currentHex}, ${expectedHex})`,
                    }}
                  />
                </div>
                {/* Current position pin */}
                <div
                  className="absolute top-1/2 w-5 h-5 rounded-full border-4 bg-white shadow-md z-10"
                  style={{
                    left: `${currentPos * 100}%`,
                    transform: "translateX(-50%) translateY(-50%)",
                    borderColor: currentHex,
                  }}
                />
              </div>

              {/* SAP gain + cost */}
              <div className="flex items-end justify-between pt-1">
                <div>
                  <span className="font-manrope font-black text-2xl text-brandblue tabular-nums">
                    +{sapImprovement}
                  </span>
                  <span className="text-sm font-medium text-gray-400 ml-1.5">
                    SAP Gain
                  </span>
                </div>
                <div className="text-right">
                  <p className="text-xs text-gray-400 font-medium mb-0.5">
                    Estimated Investment
                  </p>
                  <span className="font-manrope font-black text-2xl text-brandblue tabular-nums">
                    £{formatNumber(totalEstimatedCost)}
                  </span>
                </div>
              </div>
            </div>

            {/* CTA button */}
            <div className="flex justify-end mt-auto">
              <button
                type="button"
                onClick={() => router.push(`${pathname}/${planId}`)}
                className="py-2.5 px-6 rounded-xl bg-brandblue text-white font-manrope font-bold text-sm hover:bg-hoverblue transition-colors active:scale-95 flex items-center gap-2"
              >
                View Plan
                <ArrowRightIcon className="w-4 h-4" />
              </button>
            </div>
          </div>

          {/* Right: image */}
          <div className="w-full md:w-64 h-56 md:h-auto rounded-xl overflow-hidden flex-shrink-0">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="https://lh3.googleusercontent.com/aida-public/AB6AXuD3ciUtcps6C-Cimp8GUpI-SmEjXEAyrwoPfhhVGV2-q_4KV1pYKqP1zGAVF7mN4NYLVsKIRW4qSphWvqwSOTbnEtT_ogwJ_jz1bSFbUG34gG_dVpBLjMGuo2yFlgVWDZDPFFbm2j5HQtRcXQemDnyQ6uHb8oxqhSu8_duOWSUGMcWPZAR_pPUUOoGd9g5hCjf00Amhs6GE61LlTM0U7B0hrKB58570DMDK_5mwabLnEF0W2sFV6ADwcIZpt_ZJuE0dMp3YzvEPjiBz"
              alt="Modern architectural house exterior"
              className="w-full h-full object-cover"
            />
          </div>
        </div>

        {/* ── Impact card ─────────────────────────────── */}
        <div className="lg:col-span-4 bg-gradient-to-br from-brandblue to-[#0a2a4a] text-white rounded-2xl p-8 flex flex-col justify-between shadow-sm border border-white/10">
          <div className="space-y-6">
            <h3 className="font-manrope font-bold text-xl">Impact</h3>

            {/* CO2 */}
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-white/15 flex items-center justify-center flex-shrink-0">
                <svg
                  className="w-5 h-5 text-white"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path d="M12 2a7 7 0 017 7c0 5-7 13-7 13S5 14 5 9a7 7 0 017-7z" />
                  <circle cx="12" cy="9" r="2.5" />
                </svg>
              </div>
              <div className="flex-1">
                <p className="text-xs text-white/60 font-medium">
                  Annual CO₂ Reduction
                </p>
                <div className="flex items-center gap-2">
                  <p className="font-manrope font-bold text-lg">
                    {co2Savings != null
                      ? `${co2Savings.toFixed(1)} Tonnes`
                      : "—"}
                  </p>
                  {carsEquivalent != null && carsEquivalent > 0 && (
                    <div className="relative group/co2tooltip">
                      <button
                        type="button"
                        className="w-4 h-4 rounded-full bg-white/25 flex items-center justify-center text-white hover:bg-white/40 transition-colors cursor-help flex-shrink-0"
                        tabIndex={-1}
                        aria-label="Carbon equivalent info"
                      >
                        <span className="text-[9px] font-black leading-none">
                          !
                        </span>
                      </button>
                      <div className="pointer-events-none absolute left-1/2 -translate-x-1/2 bottom-full mb-3 w-64 opacity-0 group-hover/co2tooltip:opacity-100 transition-opacity z-30">
                        <div className="bg-white rounded-2xl shadow-2xl p-4 border border-gray-100">
                          <div className="flex items-center gap-2 mb-2">
                            <div className="w-7 h-7 rounded-full bg-brandblue/8 flex items-center justify-center flex-shrink-0">
                              <svg
                                className="w-3.5 h-3.5 text-brandblue"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth={2}
                              >
                                <path d="M5 17H3a1 1 0 01-1-1v-4l2.5-5h11L18 12v4a1 1 0 01-1 1h-2" />
                                <circle cx="7.5" cy="17.5" r="1.5" />
                                <circle cx="16.5" cy="17.5" r="1.5" />
                                <path d="M5 12h14" />
                              </svg>
                            </div>
                            <p className="text-xs font-bold text-brandblue">
                              Equivalent Impact
                            </p>
                          </div>
                          <p className="text-xs text-gray-500 leading-relaxed">
                            Like taking{" "}
                            <span className="font-bold text-brandblue">
                              ~{carsEquivalent} car
                              {carsEquivalent !== 1 ? "s" : ""}
                            </span>{" "}
                            off the road for a year — based on the avg. UK car
                            emitting 1.47 t CO₂/yr.
                          </p>
                        </div>
                        {/* Caret */}
                        <div className="flex justify-center">
                          <div className="w-3 h-1.5 overflow-hidden">
                            <div className="w-3 h-3 bg-white border border-gray-100 rotate-45 -translate-y-1.5 shadow-sm" />
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Bill savings */}
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-white/15 flex items-center justify-center flex-shrink-0">
                <svg
                  className="w-5 h-5 text-white"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <rect x="2" y="5" width="20" height="14" rx="2" />
                  <path d="M2 10h20" />
                </svg>
              </div>
              <div>
                <p className="text-xs text-white/60 font-medium">
                  Bill Savings (Est.)
                </p>
                <p className="font-manrope font-bold text-lg">
                  {energyBillSavings != null
                    ? `£${formatNumber(energyBillSavings)} / yr`
                    : "—"}
                </p>
              </div>
            </div>

            {/* Valuation uplift */}
            {(valuationIncreaseLowerBound != null ||
              valuationIncreaseUpperBound != null) && (
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-white/15 flex items-center justify-center flex-shrink-0">
                  <svg
                    className="w-5 h-5 text-white"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z" />
                    <path d="M9 22V12h6v10" />
                    <path d="M12 7v5m0 0l-2-2m2 2l2-2" />
                  </svg>
                </div>
                <div>
                  <p className="text-xs text-white/60 font-medium">
                    Valuation Uplift (Est.)
                  </p>
                  <p className="font-manrope font-bold text-lg">
                    {valuationIncreaseLowerBound != null &&
                    valuationIncreaseUpperBound != null
                      ? `${formatNumber(valuationIncreaseLowerBound * 100)}% – ${formatNumber(valuationIncreaseUpperBound * 100)}%`
                      : valuationIncreaseLowerBound != null
                        ? `${formatNumber(valuationIncreaseLowerBound * 100)}%+`
                        : `Up to ${formatNumber(valuationIncreaseUpperBound! * 100)}%`}
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Delete modal */}
      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="text-red-600">Delete plan</DialogTitle>
          </DialogHeader>
          {previewLoading ? (
            <p className="text-sm text-gray-500">Loading deletion preview…</p>
          ) : previewError ? (
            <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={() => setDeleteOpen(false)}
              disabled={deleteMutation.isPending}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteMutation.mutate()}
              disabled={deleteMutation.isPending}
            >
              {deleteMutation.isPending ? "Deleting…" : "Delete plan"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
