"use client";

import { useState } from "react";
import React from "react";
import { FundingPackageWithMeasures } from "@/app/db/schema/funding";
import { formatNumber } from "@/app/utils";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import { Button } from "@/app/shadcn_components/ui/button";
import { PiggyBank } from "lucide-react";
import { Dialog, Transition } from "@headlessui/react";
import { Fragment } from "react";
import { FundingPackageMeasure } from "@/app/db/schema/funding";

type FundingSummaryProps = {
  scheme: string | null;
  onSeeMore: () => void;
};

export const FundingSummary: React.FC<FundingSummaryProps> = ({
  scheme,
  onSeeMore,
}) => {
  let message: string | null = null;

  if (!scheme) {
    message = "Funding not assessed for this measure package";
  } else if (scheme.toLowerCase() === "none") {
    message = "Funding not eligible for this measure package";
  }

  return (
    <Card className="w-full max-w-sm bg-brandblue border-none shadow-none">
      <CardContent className="p-4 flex flex-col items-center text-center space-y-2">
        {message ? (
          <p className="text-sm text-brandbrown">{message}</p>
        ) : (
          <>
            <div className="flex items-center gap-2 text-xl font-semibold uppercase tracking-wide text-brandbrown">
              <span>{scheme}</span>
              <PiggyBank className="h-5 w-5 text-brandbrown" />
            </div>
            <p className="text-sm text-white max-w-xs">
              Click below to learn more about available funding options.
            </p>
            {!message && (
              <Button
                variant="ghost"
                size="sm"
                onClick={onSeeMore}
                className="text-brandbrown hover:bg-brandbrown hover:text-brandblue"
              >
                See More
              </Button>
            )}
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default function ValuationImpactComponent({
  currentValuation,
  valuationIncreaseLowerBound,
  valuationIncreaseUpperBound,
  funding,
}: {
  currentValuation: number | null;
  valuationIncreaseLowerBound: number | null;
  valuationIncreaseUpperBound: number | null;
  funding: FundingPackageWithMeasures;
}) {
  const [fundingModalIsOpen, setFundingModalIsOpen] = useState(false);

  const lowerBoundValuation =
    currentValuation && valuationIncreaseLowerBound
      ? currentValuation + valuationIncreaseLowerBound
      : null;

  const upperBoundValuation =
    currentValuation && valuationIncreaseUpperBound
      ? currentValuation + valuationIncreaseUpperBound
      : null;

  function openFundingModal() {
    setFundingModalIsOpen(true);
  }

  function formatPercent(value: number | null): string {
    if (value === null || isNaN(value)) return "–";
    const percent = value * 100;
    // Show no decimals if it's a whole number, otherwise 1 decimal
    return Number.isInteger(percent) ? percent.toString() : percent.toFixed(1);
  }

  return (
    <div className="col-span-1 md:col-span-2 lg:col-span-3 w-full p-4 bg-brandblue rounded-lg shadow-md grid grid-cols-1 md:grid-cols-3 gap-6">
      {/* Current Valuation */}
      <div className="flex flex-col items-center justify-center text-center h-full space-y-1">
        <span className="text-gray-100 text-lg">Current Property Value</span>
        <span className="text-3xl font-bold text-brandbrown">
          {currentValuation
            ? `£${formatNumber(currentValuation)}`
            : "Not available"}
        </span>
      </div>

      {/* After Retrofit Valuation */}
      <div className="flex flex-col items-center justify-center text-center space-y-1">
        <span className="text-gray-100 text-lg">After Retrofit Valuation</span>

        {currentValuation && lowerBoundValuation && upperBoundValuation ? (
          // CASE 1: Absolute £ valuations available
          <>
            <div className="text-2xl text-brandbrown font-bold">
              £{formatNumber(lowerBoundValuation)} - £
              {formatNumber(upperBoundValuation)}
            </div>
            <span className="text-gray-100 text-lg">
              Estimated improvement:
            </span>
            <span className="text-brandbrown font-bold">
              £{formatNumber(valuationIncreaseLowerBound || 0)} - £
              {formatNumber(valuationIncreaseUpperBound || 0)}
            </span>
          </>
        ) : valuationIncreaseLowerBound !== null &&
          valuationIncreaseUpperBound !== null ? (
          // CASE 2: No base valuation, show % improvement
          <>
            <div className="text-2xl font-bold text-brandbrown flex items-baseline justify-center">
              <span className="text-3xl font-extrabold text-brandbrown mr-1">
                +
              </span>
              <span>{formatPercent(valuationIncreaseLowerBound)}</span>
              <span className="mx-1">–</span>
              <span>{formatPercent(valuationIncreaseUpperBound)}</span>
              <span className="ml-1">%</span>
            </div>

            <span className="text-gray-100 text-lg">
              Estimated value improvement
            </span>
          </>
        ) : (
          // CASE 3: Nothing available
          <span className="text-lg text-gray-300 italic">Not available</span>
        )}
      </div>

      {/* Funding summary always shown */}
      <FundingSummary scheme={funding?.scheme} onSeeMore={openFundingModal} />
      <FundingSummaryModal
        isOpen={fundingModalIsOpen}
        closeModal={() => setFundingModalIsOpen(false)}
        scheme={funding?.scheme}
        fundingPackageMeasures={funding?.fundingPackageMeasures || []}
      />
    </div>
  );
}

type FundingSummaryModalProps = {
  isOpen: boolean;
  closeModal: () => void;
  scheme?: string | null;
  fundingPackageMeasures: FundingPackageMeasure[];
};

export function FundingSummaryModal({
  isOpen,
  closeModal,
  scheme,
  fundingPackageMeasures,
}: FundingSummaryModalProps) {
  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-50" onClose={closeModal}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-200"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-150"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black bg-opacity-30" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4 text-center">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-lg transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                <Dialog.Title className="text-xl font-semibold text-brandblue flex items-center gap-2 mb-4">
                  <PiggyBank className="h-5 w-5 text-brandbrown" />
                  {scheme?.toUpperCase() || "Funding Details"}
                </Dialog.Title>

                <p className="text-sm text-gray-700 mb-4">
                  This package has been optimised to meet the eligibility
                  criteria of the <strong>{scheme?.toUpperCase()}</strong>{" "}
                  funding scheme. Measures have been selected to maximise the
                  property’s improvement while minimising cost and ensuring
                  compliance.
                </p>

                <div className="mb-4">
                  <h4 className="text-sm font-semibold text-brandblue mb-2">
                    Included Measures
                  </h4>
                  <ul className="list-disc list-inside text-sm text-gray-800 space-y-1">
                    {fundingPackageMeasures.map((measure) => (
                      <li key={measure.id.toString()}>
                        {measure.measure.replace(/_/g, " ")}
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="mt-6 flex justify-end">
                  <button
                    type="button"
                    onClick={closeModal}
                    className="inline-flex justify-center rounded-md bg-brandblue px-4 py-2 text-sm font-medium text-white hover:bg-hoverblue focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                  >
                    Close
                  </button>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}
