import { Dialog, Transition } from "@headlessui/react";
import React, { Fragment, useState } from "react";
import PoundIconSvg from "./PoundIconSvg";
import LightBulbSvg from "./LightBulbSvg";
import CarbonIcon from "./CarbonIcon";
import QuestionMarkIcon from "./QuestionMarkIcon";
import EnvironmentIcon from "./EnvironmentIconSvg";
import ModalSubmit from "./ModalSubmit";
import { PortfolioGoal } from "@/app/db/schema/portfolio";

// Mock Icon component
interface IconProps {
  name: string;
  selected: boolean;
  onSelect: (name: string) => void;
  className?: string;
}

const selectedIconClasses =
  "bg-brandblue w-1/5 rounded-md h-1/5 cursor-pointer";
const deSelectedIconClasses =
  "bg-gray-200 w-1/5 rounded-md h-1/5 cursor-pointer";

interface IconComponentsType {
  [key: string]: React.ReactElement;
}

const Icon: React.FC<IconProps> = ({ name, selected, onSelect }: IconProps) => {
  const iconComponents: IconComponentsType = {
    "Valuation Improvement": <PoundIconSvg fill="white" />,
    "Energy Savings": <LightBulbSvg fill="white" />,
    // add more mappings here if needed
    "Increasing EPC": <EnvironmentIcon fill="white" />,
    "Reducing CO2 emissions": <CarbonIcon fill="white" />,
    None: <QuestionMarkIcon fill="white" />,
  };

  return (
    <div
      onClick={() => onSelect(name)}
      className={selected ? selectedIconClasses : deSelectedIconClasses}
    >
      {iconComponents[name]}
      <div className="flex items-center justify-center bg-gray-200 text-center text-sm h-10 rounded-bl-md rounded-br-md">
        {name}
      </div>
    </div>
  );
};

const hiddenInputArrows =
  "[-moz-appearance:_textfield] [&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none";

export default function NewPortfolioModal({
  isOpen = false,
  setIsOpen,
}: {
  isOpen?: boolean;
  setIsOpen: (isOpen: boolean) => void;
}) {
  const [portfolioName, setPortfolioName] = useState("");
  const [budget, setBudget] = useState<undefined | number>(undefined);
  const [selectedOutcome, setSelectedOutcome] = useState<string>("None");
  const [buttonDisabled, setButtonDisabled] = useState(true);

  function closeModal() {
    setIsOpen(false);
  }

  function handlePortfolioNameChange(e: React.ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length > 0) {
      setButtonDisabled(false);
    } else {
      setButtonDisabled(true);
    }
    setPortfolioName(e.target.value);
  }

  return (
    <>
      <Transition appear show={isOpen} as={Fragment}>
        <Dialog as="div" className="relative z-10" onClose={closeModal}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-black bg-opacity-25" />
          </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-screen-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                  <Dialog.Title
                    as="h3"
                    className="text-lg font-medium leading-6 text-brandblue mb-3"
                  >
                    Create a new portfolio
                  </Dialog.Title>
                  <form className="space-y-4">
                    <div className="flex flex-col">
                      <label
                        htmlFor="portfolio-name"
                        className="text-sm font-semibold text-gray-600 mb-1 relative"
                      >
                        Portfolio Name:
                        <span className="text-red-500">*</span>
                      </label>
                      <input
                        id="portfolio-name"
                        type="text"
                        placeholder="My new portfolio"
                        required
                        value={portfolioName}
                        onChange={(e) => handlePortfolioNameChange(e)}
                        className="p-2 border border-gray-200 rounded-md focus:outline-none bg-gray-100"
                      />
                    </div>
                    <div className="flex flex-col">
                      <label
                        htmlFor="budget"
                        className="text-sm font-semibold text-gray-600 mb-1"
                      >
                        Budget (£){" "}
                        <span className="text-gray-400 text-xs">optional</span>{" "}
                        :
                      </label>
                      <div className="flex items-center border border-gray-200 rounded-md text-gray-900 bg-brandblue">
                        <span className="px-2 text-sm text-white">£</span>
                        <input
                          id="budget"
                          type="number"
                          placeholder="1000"
                          value={budget}
                          onChange={(e) => setBudget(Number(e.target.value))}
                          onKeyDown={(e) =>
                            (e.key === "e" || e.key === "E") &&
                            e.preventDefault()
                          }
                          className={[
                            "flex-1 p-2 bg-gray-100 focus:outline-none",
                            hiddenInputArrows,
                          ].join(" ")}
                        />
                      </div>
                    </div>
                    <div className="flex flex-col space-y-2">
                      <span className="text-sm font-semibold text-gray-600">
                        Select Outcome:
                      </span>
                      <div className="flex space-x-2">
                        {PortfolioGoal.map((outcome) => (
                          <Icon
                            key={outcome}
                            name={outcome}
                            selected={selectedOutcome === outcome}
                            onSelect={setSelectedOutcome}
                          />
                        ))}
                      </div>
                    </div>
                  </form>

                  <div className="mt-4 flex justify-end gap-2">
                    <button
                      type="button"
                      className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                      onClick={closeModal}
                    >
                      Cancel
                    </button>
                    <ModalSubmit
                      buttonDisabled={buttonDisabled}
                      portfolioName={portfolioName}
                      budget={budget}
                      objective={selectedOutcome}
                    />
                  </div>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition>
    </>
  );
}
