/* eslint-disable @typescript-eslint/no-explicit-any */
import { ErrorMessage, Field, Form, Formik } from "formik";
import React from "react";
import { initialValues, validationSchema } from "./FormMethods/Validation";
import { Row } from "react-bootstrap";
import { FormFeild } from "./DataListItems";
import { addModalInitialValuesHandler, SubmitHandler } from "./FormMethods/SubmitHandlers";
import { getMasterList } from "../../../Api/MastersApi";
import SelectField from "../../TextField/ReactSelect";
import HourGlassLoader from "../../Loader/Loader";
export interface Option {
  id: string;
  name: string;
}
const AddEditFrom = ({ toggle, editUser }: any) => {
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  const [roads, setRoads] = React.useState<any[]>([]);
  const [blocks, setBlocks] = React.useState<any[]>([]);
  const [buildings, setBuildings] = React.useState<any[]>([]);
  const [nationalities, setNationalities] = React.useState<any[]>([]);
  const [cities, setCities] = React.useState<any[]>([]);
  const [countries, setCountries] = React.useState<any[]>([]);
  const [addModalInitialValues, setAddModalInitialValues] = React.useState(initialValues);
  React.useEffect(() => {
    if(editUser?.id) {
      addModalInitialValuesHandler(editUser, setAddModalInitialValues);
    } else setAddModalInitialValues(initialValues);
  },[editUser])
  React.useEffect(() => {
    const fetchMasterLists = async () => {
      try {
        setIsLoading(true);
        const [road, block, building, nat, city, country] = await Promise.all([
          getMasterList("road"),
          getMasterList("block"),
          getMasterList("building"),
          getMasterList("nationality"),
          getMasterList("country"),
          getMasterList("city"),
        ]);
        setRoads(road.data || []);
        setBlocks(block.data || []);
        setBuildings(building.data || []);
        setNationalities(nat.data || []);
        setCountries(country.data?.data || []);
        setCities(city.data?.data || []);
      } catch (err) {
        console.error("Error loading masterlists", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMasterLists();
  }, []);
  return (
    <>
      <style>
        {`
          /* styles.css or globals.css */

          .custom-center-modal.modal-dialog {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0 auto;
          }
          .red_color{ color:red; }
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .modal-dialog {
              display: flex;
              align-items: center;
              min-height: calc(100% - var(--bs-modal-margin) * 2);
              position: relative;
              margin: var(--bs-modal-margin);
              width: 1020px;
              max-width: 1020px;
              margin-right: auto;
              margin-left: auto;
            }
            .bottom-sheet-modal .modal-content {
              border-radius: 1.5rem 1.5rem 1.5rem 1.5rem;
            }
          }

          @media only screen and (min-device-width : 100px) and (max-device-width : 767px) {
            .row-add-staff {
              max-height: 65.5vh;
              overflow-y: auto;
              padding-top: 6px;
            }
              .close-menu { margin-bottom: 20px!important; }
          }
            .css-b62m3t-container {
                position: unset;
            }
          .react-select__control, .css-2ubb82-control {
            border-radius: 10px;
            position: unset!important;
          }
          .input-style-select .react-select__input-container input.react-select__input {
            cursor: text;
            padding-left: 0px !important;
            padding-right: 0px !important;
            min-width: auto!important;
            overflow: hidden!important;
            height: -webkit-fill-available;
          }
          .input-style-select .input-icon { display: none; }
          // span.error-message { margin-right: 0; right: 0; }
          .react-select__value-container.css-185ylxh {
              height: 52px;
          }
          .react-select__input-container, .css-5q2sn7 {
              height: 42px;
          }
          .input-style.has-borders input[type="file"] {
            padding: 15px 0px;
            padding-left: 25px !important;
            height: auto;
            line-height: 1.75;
          }

        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div
        id="add-address"
        data-menu-effect="menu-over"
        style={{ maxHeight: 555 }}
      >
        <div className="menu-title">
          <h1 className="font-24">{editUser?.id ? "Edit Staff" : "Add Staff"}</h1>
          {/* <a href="#" className="close-menu"><i className="fa fa-times" /></a> */}
        </div>
        <div className="content mb-0 mt-0">
          <Formik
            enableReinitialize={true}
            initialValues={addModalInitialValues}
            validationSchema={validationSchema}
            onSubmit={(values, actions) => {
              SubmitHandler(values, actions, toggle, addModalInitialValues);
            }}
          >
            {({ values, errors, setFieldValue }: any) => {
              const handleSelectChange =
                (fieldName: any) => (option: Option | null) => {
                  setFieldValue(fieldName?.name, option?.id || "");
                };

              const getOptions = (type: string): Option[] => {
                switch (type) {
                  case "block":
                    return blocks;
                  case "road":
                    return roads;
                  case "building":
                    return buildings;
                  case "nationality":
                    return nationalities;
                  case "city":
                    return cities;
                  case "country":
                    return countries;
                  default:
                    return [];
                }
              };
              return (
                <Form>
                  <Row className="row-add-staff mb-0">
                    {FormFeild?.map((item: any, index: number) => {
                      return (
                        <div className="col-lg-4" key={index}>
                          <div
                            key={index}
                            className="input-style input-style-always-active has-borders has-icon validate-field"
                          >
                            <i
                              className={`fa fa-${item?.icon} color-blue-dark`}
                            />
                            {item.select ? (
                              <>
                                <SelectField
                                  options={getOptions(item.name)}
                                  value={
                                    getOptions(item.name).find(
                                      (opt) => opt.id === values[item.name]
                                    ) || null
                                  }
                                  onChange={handleSelectChange(item)}
                                  placeholder={`Select ${item.label}`}
                                  isCreatable={true}
                                  width="100%"
                                  errors={errors[item.name]}
                                  usageType={0}
                                  icon={item.icon}
                                />
                              </>
                            ) : item.type === "file" ? (
                              <input
                                type="file"
                                name={item.name}
                                className="form-control"
                                onChange={(event) => {
                                  setFieldValue(
                                    item.name,
                                    event.currentTarget.files?.[0]
                                  );
                                }}
                              />
                            ) : (
                              <Field
                                type={item.type || "text"}
                                className="form-control validate-name"
                                id={item.name}
                                placeholder={
                                  item.placeholder || `Enter ${item.label}`
                                }
                                name={item.name}
                              />
                            )}
                            <label
                              htmlFor={item.name}
                              className="color-theme opacity-50 text-uppercase font-700 font-10"
                            >
                              {item.label}
                            </label>
                            <span className="error-message">
                              <ErrorMessage
                                name={item.name}
                                component="div"
                                className="red_color"
                              />
                            </span>
                          </div>
                        </div>
                      );
                    })}
                  </Row>
                  <div className="col-12 text-end pt-2">
                    <button
                      type="submit"
                      className="close-menu btn btn-full btn-m shadow-l rounded-s font-600 bg-blue-dark mb-2 w-100"
                    >
                      Submit
                    </button>
                  </div>
                </Form>
              );
            }}
          </Formik>
        </div>
      </div>
    </>
  );
};
export default AddEditFrom;
