"use client";

import { useState, useTransition } from "react";
import { useRouter, usePathname } from "next/navigation";
import {
  NewspaperIcon,
  HomeModernIcon,
  WrenchScrewdriverIcon,
  CircleStackIcon,
  HeartIcon,
  ArrowPathIcon,
  ClipboardDocumentCheckIcon,
} from "@heroicons/react/24/outline";
import { cn } from "@/lib/utils";
import { getUploadedFile } from "@/app/db/surveyDB/schema/surveyDB";
import BookSurveyModal from "@/app/portfolio/[slug]/components/BookSurveyModal";
import SuccessToast from "@/app/portfolio/[slug]/components/SuccessToast";
import { PropertyMeta } from "@/app/db/schema/property";

interface ToolbarProps {
  propertyId: string;
  portfolioId: string;
  propertyMeta: PropertyMeta;
  decentHomes: getUploadedFile;
}

export function Toolbar({
  propertyId,
  portfolioId,
  propertyMeta,
  decentHomes,
}: ToolbarProps) {
  const [openModal, setOpenModal] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [loadingTab, setLoadingTab] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  const pathname = usePathname();

  const baseUrl = `/portfolio/${portfolioId}/building-passport/${propertyId}`;

  const tabs = [
    { href: baseUrl, label: "Overview", icon: HomeModernIcon, exact: true },
    { href: `${baseUrl}/assessment`, label: "Property Details", icon: NewspaperIcon },
    ...(Object.keys(decentHomes).length > 0 && decentHomes.uprn
      ? [{ href: `${baseUrl}/decent-homes`, label: "Decent Homes", icon: HeartIcon }]
      : []),
    { href: `${baseUrl}/plans`, label: "Retrofit Plans", icon: WrenchScrewdriverIcon },
    { href: `${baseUrl}/documents`, label: "Documents", icon: CircleStackIcon },
  ] as { href: string; label: string; icon: React.ElementType; exact?: boolean }[];

  const handleNav = (href: string) => {
    if (pathname === href) return;
    setLoadingTab(href);
    startTransition(() => {
      router.push(href);
    });
  };

  return (
    <>
      <div className="flex items-center justify-between w-full px-3 py-1.5">
        {/* Tabs */}
        <div className="flex items-center gap-0.5">
          {tabs.map((tab) => {
            const isActive = tab.exact
              ? pathname === tab.href
              : pathname.startsWith(tab.href);
            const isLoading = loadingTab === tab.href && isPending;
            const Icon = tab.icon;

            return (
              <button
                key={tab.href}
                onClick={() => handleNav(tab.href)}
                className={cn(
                  "relative flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer",
                  isActive
                    ? "bg-white text-gray-900 shadow-sm"
                    : "text-gray-500 hover:text-gray-800 hover:bg-white/70",
                )}
              >
                {isLoading ? (
                  <ArrowPathIcon className="h-4 w-4 animate-spin text-indigo-500" />
                ) : (
                  <Icon className="h-4 w-4" />
                )}
                {tab.label}
                {isActive && (
                  <span className="absolute bottom-0 left-2 right-2 h-0.5 rounded-full bg-blue-500" />
                )}
              </button>
            );
          })}
        </div>

        {/* Book Assessment button */}
        <button
          onClick={() => setOpenModal(true)}
          className="flex items-center gap-2 px-4 py-2 rounded-xl bg-gradient-to-br from-gray-900 to-gray-700 text-white text-sm font-semibold shadow-md hover:scale-[1.03] transition-transform active:scale-95 cursor-pointer"
        >
          <ClipboardDocumentCheckIcon className="h-4 w-4" />
          Book Assessment
        </button>
      </div>

      {openModal && (
        <BookSurveyModal
          open={openModal}
          onOpenChange={setOpenModal}
          propertyId={BigInt(propertyId)}
          portfolioId={portfolioId}
          propertyMeta={propertyMeta}
          onSuccess={() => setShowToast(true)}
        />
      )}

      <SuccessToast
        show={showToast}
        showConfetti={showToast}
        onClose={() => setShowToast(false)}
        message="Survey Request Recieved!"
        subtext="We'll be in contact soon. 🎉"
      />
    </>
  );
}
