import React, { useState } from "react";
import { SearchBlockProps } from "./types";

import { Button } from "@shared/components/button";
import { Input } from "@shared/components/input";
import { MaterialIcon } from "@shared/components/material-icon";
import { Text } from "@shared/components/text";
import { cx } from "@shared/utils";

export const SearchBlock: React.FC<SearchBlockProps> = props => {
  const {
    anchorId = "SearchBlock",
    title,
    subTitle,
    enableHeading,
    searchDescription,
    searchInputPlaceholder,
    basicCaption,
    caption,
    backgroundColor,
    color,
    onSubmit,
  } = props;
  const [searchText, setSearchText] = useState("");
  const themeColorClasses = {
    supporting: "bg-bg-fill-brand-supporting",
    white: "bg-bg",
    brand: "bg-bg-fill-brand",
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    onSubmit?.({ searchText });
  };

  return (
    <div
      className={`py-10 md:py-20 ${themeColorClasses[backgroundColor]} ${color == "dark" ? "text-text" : "text-white"}`}
      id={anchorId}
      data-testid="search-block"
    >
      <div className={"flex justify-center"}>
        <div className="w-[1200px]">
          <div className="mb-8 text-center">
            <Text
              as={enableHeading ? "h1" : "h2"}
              className={cx("heading2 md:heading1")}
            >
              {title}
            </Text>
            {subTitle && (
              <Text as="div" className={cx("subheading2 mt-2 md:subheading1")}>
                {subTitle}
              </Text>
            )}
          </div>
          {searchDescription ? (
            <Text className={`heading6 text-center`}>{searchDescription}</Text>
          ) : null}

          <span className="w-full">
            <form
              onSubmit={handleSubmit}
              className="flex items-center rounded-md border bg-bg transition-colors focus-within:border-border-focus"
            >
              <Button type="submit" className="ml-2 inline-flex">
                <MaterialIcon name="search" className="text-text" />
              </Button>
              <div className="flex-grow">
                <Input
                  value={searchText}
                  onChange={(e: {
                    target: { value: React.SetStateAction<string> };
                  }) => setSearchText(e.target.value)}
                  placeholder={searchInputPlaceholder}
                  containerClassName="px-4 pl-0 rounded-md flex-grow border-none"
                  className={"body3 rounded-md text-text"}
                />
              </div>
            </form>
          </span>
          {caption ? caption : null}
          {basicCaption}
        </div>
      </div>
    </div>
  );
};

export default SearchBlock;
