import React, { useState } from "react";
import { Form, Input, Select } from "antd";
import { FormInstance } from "antd/lib/form/Form";
import { Paragraph, Text } from "components/Typography";
import { CurrencyCodes } from "constants/currency-code";
import { useAutoSave } from "hooks/useAutoSave";
import CountriesLocalizationSelect from "pages/CountriesLocalizationSelect";
import { useEffect, useMemo } from "react";
import { useTypedSelector } from "redux/rootReducer";
import { selectLocalizations } from "redux/User/selector";
import { LocalizationItem as LocalizationItemType } from "redux/User/types";
import cloneDeep from "lodash/cloneDeep";
const { Option } = Select;
interface IProps {
  edit?: boolean;
  name: string;
  currency: string;
  form: FormInstance<any>;
  countries?: string[];
  onChangeCurrency: (value: string) => void;
  onChangeCountries: (values: string[]) => void;
  onPageNameChange: (value: string) => void;
}

const FirstStep = ({
  edit,
  name,
  form,
  countries,
  currency,
  onChangeCurrency,
  onChangeCountries,
  onPageNameChange,
}: IProps) => {
  const [oldName, setOldName] = useState<string>();
  const { localizationSelected } = useAutoSave();
  const localizations = useTypedSelector(selectLocalizations);
  useEffect(() => {
    setOldName(name);
  }, []);
  const localizationNames = useMemo(() => {
    if (!edit) {
      return (
        localizations?.map((locale: LocalizationItemType) => locale.name) || []
      );
    }
    return (
      localizations
        ?.filter(
          (locale: LocalizationItemType) =>
            locale.id !== localizationSelected?.id
        )
        .map((locale: LocalizationItemType) => locale.name) || []
    );
  }, [localizations, edit, localizationSelected]);

  useEffect(() => {
    form.setFieldsValue({ name });
  }, [form]);

  const handleNameChange = (event: any) => {
    const value = event.target.value;
    onPageNameChange?.(value);
    form.setFieldsValue({ name: value });
  };
  return (
    <div className="localization-create-form">
      {!edit && (
        <>
          <div className="step-info">
            <Paragraph preset="regular14" className="opacity--80">
              You are about to add a new localized page. Your page will remain
              inactive and will not be displayed in the countries selected until
              you publish it.
            </Paragraph>
          </div>
          <div className="m__t--16">
            <Text className="" preset="semibold18">
              Page Settings
            </Text>
          </div>
        </>
      )}

      <Form.Item
        name="name"
        className={edit ? "m__b--4" : "m__t--16 m__b--4"}
        label="Page name"
        rules={[
          { required: true, message: "Please enter page name" },
          oldName !== name.trim()
            ? {
                validator: (_, value) => {
                  return !localizationNames.includes(value)
                    ? Promise.resolve()
                    : (() => {
                        return Promise.reject(
                          "This page name already exists. Please enter a different name"
                        );
                      })();
                },
              }
            : {},
        ]}
      >
        <Input
          onChange={handleNameChange}
          className="height--48"
          value={name}
          defaultValue={name}
          placeholder="Enter page name"
        />
      </Form.Item>

      {/* <Text preset="regular14" className="opacity--80 m__t--4">
        This name will not be displayed to your audience
      </Text> */}

      <Form.Item
        label="Page currency"
        name="currency"
        className="m__t--16 m__b--16"
        initialValue={currency}
      >
        <Select
          className="localization-create-form__currency"
          defaultValue={currency || "USD"}
          dropdownClassName="localization-dropdown-menu"
          onChange={onChangeCurrency}
        >
          {Object.values(CurrencyCodes).map((currency, i) => (
            <Option key={currency.code} value={currency.code}>
              {currency.symbol} - {currency.code} - {currency.name}
            </Option>
          ))}
        </Select>
        <Text preset="regular14" className="opacity--80 m__t--8">
          You will still be able to manually apply different currencies to
          individual products
        </Text>
      </Form.Item>
      <Form.Item
        label="Countries"
        name="countries"
        rules={[{ required: true, message: "Please add at least one country" }]}
        initialValue={countries}
      >
        <CountriesLocalizationSelect
          className="localization__countries-select"
          values={countries}
          onChange={onChangeCountries}
          withFilter
        />
      </Form.Item>
    </div>
  );
};

export default FirstStep;
