import {
  formData,
  stepValidator,
} from "../../../../features/context/TOD.FormulaireData";
import axios from "axios";
import { useState, useEffect } from "react";
import ColorPicker from "../../../../components/colorPicker/ColorPicker";
import FilePicker from "../../../../components/FilePicker/FilePicker";
import TODInput from "../../../../components/inputs/TOD.Input";
import WBRepeater from "../../../../components/inputs/repeater/WBRepeater";
import WBRepeaterRow from "../../../../components/inputs/repeater/WBRepeaterRow";
import IconPicker from "../../../../components/inputs/icon-picker/TOD.IconPicker";

const GeneralInfo = () => {
  const [errors, setErrors] = useState({});
  const [showErrors, setShowErrors] = useState(false);

  // Validation functions
  const validateForm = () => {
    const newErrors = {};
    const generalInfo = formData.value.generalInfo;

    if (!generalInfo?.fullName?.trim()) {
      newErrors.fullName = "Your name is required";
    }
    if (!generalInfo?.businessName?.trim()) {
      newErrors.businessName = "Business name is required";
    }
    if (!generalInfo?.businessEmail?.trim()) {
      newErrors.businessEmail = "Business email is required";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(generalInfo.businessEmail)) {
      newErrors.businessEmail = "Invalid email format";
    }
    if (!generalInfo?.businessPhone?.trim()) {
      newErrors.businessPhone = "Business phone is required";
    } else if (
      !/^\+?1?\s*\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$/.test(
        generalInfo.businessPhone
      )
    ) {
      newErrors.businessPhone = "Invalid phone format";
    }

    setErrors(newErrors);
    setShowErrors(true);
    return Object.keys(newErrors).length === 0;
  };

  useEffect(() => {
    stepValidator.value.fn = validateForm;
    return () => {
      stepValidator.value.fn = () => true;
      setShowErrors(false);
    };
  }, []);

  const handleChange = (field, value) => {
    formData.value = {
      ...formData.value,
      generalInfo: {
        ...formData.value["generalInfo"],
        [field]: value,
      },
    };
  };

  // Social Media functions
  const addSocialMedia = () => {
    const currentSocialMedia = formData.value.generalInfo?.socialMedia || [];
    handleChange("socialMedia", [...currentSocialMedia, { icon: "", url: "" }]);
  };

  const updateSocialMedia = (index, field, value) => {
    const currentSocialMedia = [
      ...(formData.value.generalInfo?.socialMedia || []),
    ];
    currentSocialMedia[index] = {
      ...currentSocialMedia[index],
      [field]: value,
    };
    handleChange("socialMedia", currentSocialMedia);
  };

  const deleteSocialMedia = (index) => {
    const currentSocialMedia = [
      ...(formData.value.generalInfo?.socialMedia || []),
    ];
    currentSocialMedia.splice(index, 1);
    handleChange("socialMedia", currentSocialMedia);
  };

  const reorderSocialMedia = (index, direction) => {
    const currentSocialMedia = [
      ...(formData.value.generalInfo?.socialMedia || []),
    ];
    const newIndex = direction === "up" ? index - 1 : index + 1;

    if (newIndex >= 0 && newIndex < currentSocialMedia.length) {
      [currentSocialMedia[index], currentSocialMedia[newIndex]] = [
        currentSocialMedia[newIndex],
        currentSocialMedia[index],
      ];
      handleChange("socialMedia", currentSocialMedia);
    }
  };

  // Review Platform functions
  const addReviewPlatform = () => {
    const currentPlatforms = formData.value.generalInfo?.reviewPlatforms || [];
    handleChange("reviewPlatforms", [
      ...currentPlatforms,
      { icon: "", url: "" },
    ]);
  };

  const updateReviewPlatform = (index, field, value) => {
    const currentPlatforms = [
      ...(formData.value.generalInfo?.reviewPlatforms || []),
    ];
    currentPlatforms[index] = {
      ...currentPlatforms[index],
      [field]: value,
    };
    handleChange("reviewPlatforms", currentPlatforms);
  };

  const deleteReviewPlatform = (index) => {
    const currentPlatforms = [
      ...(formData.value.generalInfo?.reviewPlatforms || []),
    ];
    currentPlatforms.splice(index, 1);
    handleChange("reviewPlatforms", currentPlatforms);
  };

  const reorderReviewPlatform = (index, direction) => {
    const currentPlatforms = [
      ...(formData.value.generalInfo?.reviewPlatforms || []),
    ];
    const newIndex = direction === "up" ? index - 1 : index + 1;

    if (newIndex >= 0 && newIndex < currentPlatforms.length) {
      [currentPlatforms[index], currentPlatforms[newIndex]] = [
        currentPlatforms[newIndex],
        currentPlatforms[index],
      ];
      handleChange("reviewPlatforms", currentPlatforms);
    }
  };

  const saveLatLongFromAddress = (address) => {
    if (!address) return;

    const key = "AIzaSyAdNRSwe0S08EDF4UcExqk74RgvgQUv50U";
    axios
      .get(
        "https://maps.googleapis.com/maps/api/geocode/json?address=" +
        encodeURIComponent(address) +
        "&key=" +
        key
      )
      .then((response) => {
        if (
          response.data &&
          response.data.status == "OK" &&
          response.data.results[0] &&
          response.data.results[0].geometry &&
          response.data.results[0].geometry.location &&
          response.data.results[0].geometry.location.lat
        ) {
          handleChange("latlng", {
            lat: response.data.results[0].geometry.location.lat,
            lng: response.data.results[0].geometry.location.lng,
          });
        }
      });
  };

  return (
    <div className="form-container">
      <div className="form-header">
        <h2>1. Add Logo, General Business and Contact Information</h2>
        <p>
          Enter your business information below. We will use that information
          throughought the website as needed.
        </p>
      </div>

      <div className="form-grid">
        <TODInput
          type="text"
          name="fullName"
          label="Full Name"
          placeholder="Full name"
          value={formData.value.generalInfo?.fullName || ""}
          onChange={(value) => handleChange("fullName", value)}
          error={showErrors ? errors.fullName : null}
          required
        />

        <TODInput
          type="text"
          name="businessName"
          label="Business Name"
          placeholder="My Awesome Business"
          value={formData.value.generalInfo?.businessName || ""}
          onChange={(value) => handleChange("businessName", value)}
          error={showErrors ? errors.businessName : null}
          required
        />

        <TODInput
          type="email"
          name="businessEmail"
          label="Business Email"
          placeholder="contact@business.com"
          value={formData.value.generalInfo?.businessEmail || ""}
          onChange={(value) => handleChange("businessEmail", value)}
          error={showErrors ? errors.businessEmail : null}
          details="This email will be visible on the website"
          required
        />

        <TODInput
          type="tel"
          name="businessPhone Number"
          label="Business Phone"
          placeholder="+1 (123) 456-7890"
          value={formData.value.generalInfo?.businessPhone || ""}
          onChange={(value) => handleChange("businessPhone", value)}
          error={showErrors ? errors.businessPhone : null}
          details="This phone number will be visible on the website"
          required
        />

        <div className="form-group" style={{ gridColumn: "1 / -1" }}>
          <TODInput
            type="text"
            name="businessAddress"
            label="Business Address"
            details="This address will be visible on the website. Leave this field empty if you do not wish to show your address."
            placeholder="123 Business Street"
            value={formData.value.generalInfo?.businessAddress || ""}
            onChange={(value) => handleChange("businessAddress", value)}
            onBlur={(e) => saveLatLongFromAddress(e.target.value)}
          />
        </div>

        <div className="form-group" style={{ gridColumn: "1 / -1" }}>
          <label className="form-label">Business Logo</label>
          <FilePicker
            value={formData.value.generalInfo?.businessLogo}
            setValue={(url) => handleChange("businessLogo", url)}
            label={{
              choose: "Choose a logo",
              change: "Change logo",
              current: "Your logo",
              cancel: "Cancel",
            }}
          />
          <span class="input-details">
            Ideally a .png file without a background, maximum 512px wide or
            tall.
          </span>
        </div>

        <div className="form-group" style={{ gridColumn: "1 / -1" }}>
          <label className="form-label">Square logo</label>
          <FilePicker
            value={formData.value.generalInfo?.favicon}
            setValue={(url) => handleChange("favicon", url)}
            accept=".ico,.png, .jpeg"
            previewStyle={{ marginTop: "1rem", maxWidth: "64px" }}
            label={{
              choose: "Choose a square logo",
              change: "Change square logo",
              current: "Your square logo",
              cancel: "Cancel",
            }}
          />
          <span class="input-details">
            Square logo icon displayed in web browser. Should be a .png or .jpeg
            image of square dimension (512px by 512px).
          </span>
        </div>

        <div className="form-group">
          <label className="form-label">Primary Website Color</label>
          <ColorPicker
            color={formData.value.generalInfo?.primaryColor}
            onChange={(color) => handleChange("primaryColor", color)}
          />
          <span class="input-details">
            This is the main color userd throughout the website. A color that
            has good contrast with white works best.
          </span>
        </div>

        <div className="form-group">
          <label className="form-label">Secondary Website Color</label>
          <ColorPicker
            color={formData.value.generalInfo?.secondaryColor}
            onChange={(color) => handleChange("secondaryColor", color)}
          />
          <span class="input-details">
            This is the main color userd throughout the website.
          </span>
        </div>

        <div className="form-group" style={{ gridColumn: "1 / -1" }}>
          <label className="form-label">Business Social Media Links</label>
          <span class="input-details">
            If your business has social media profiles, provide links to them
            here, otherwise you can leave this empty. Adding social media back
            links also helps increase your searchability and ranking with search
            engines such as Google. We encourage you to add as many as possible.
            (You can always do this later).
          </span>
          <WBRepeater addClick={addSocialMedia}>
            {(formData.value.generalInfo?.socialMedia || []).map(
              (social, index) => (
                <WBRepeaterRow
                  key={index}
                  index={index}
                  onDelete={deleteSocialMedia}
                  onChangeOrder={reorderSocialMedia}
                  title={social.url || `Social Media ${index + 1}`}
                  isAccordion={true}
                >
                  <div className="form-group">
                    <div className="form-group-row">
                      <IconPicker
                        value={social.icon}
                        onChange={(value) =>
                          updateSocialMedia(index, "icon", value)
                        }
                        label="Select Icon"
                        category="brand"
                      />
                    </div>
                  </div>
                  <div className="form-group-row">
                    <TODInput
                      type="url"
                      value={social.url}
                      onChange={(value) =>
                        updateSocialMedia(index, "url", value)
                      }
                      placeholder="https://..."
                      label="URL"
                    />
                  </div>
                </WBRepeaterRow>
              )
            )}
          </WBRepeater>
        </div>

        <div className="form-group" style={{ gridColumn: "1 / -1" }}>
          <label className="form-label">
            Links to platforms where your Customers can leave you a review
          </label>
          <span class="input-details">
            Add url links for each social media platform (example Google, Yelp,
            Facebook, etc) where your customers can leave your business a
            review. Getting frequent customer reviews across multiple platforms
            is a great way to boost customer trust, increase conversions and
            improve ranking with search engines. Check out the Marketplace in
            your MioCommerce account to get access to various “request a review
            and listing features”
          </span>
          <WBRepeater addClick={addReviewPlatform}>
            {(formData.value.generalInfo?.reviewPlatforms || []).map(
              (platform, index) => (
                <WBRepeaterRow
                  key={index}
                  index={index}
                  onDelete={deleteReviewPlatform}
                  onChangeOrder={reorderReviewPlatform}
                  title={platform.url || `Review Platform ${index + 1}`}
                  isAccordion={true}
                >
                  <div className="form-group">
                    <div className="form-group-row">
                      <IconPicker
                        value={platform.icon}
                        onChange={(value) =>
                          updateReviewPlatform(index, "icon", value)
                        }
                        label="Select Icon"
                        category="brand"
                      />
                    </div>
                  </div>
                  <div className="form-group-row">
                    <TODInput
                      type="url"
                      value={platform.url}
                      onChange={(value) =>
                        updateReviewPlatform(index, "url", value)
                      }
                      placeholder="https://..."
                      label="URL"
                    />
                  </div>
                </WBRepeaterRow>
              )
            )}
          </WBRepeater>
        </div>
      </div>
    </div>
  );
};

export default GeneralInfo;
