import React, { useState, useEffect } from "react";
import "./DomainForm.css";

const DOMAIN_PROVIDERS = [
  { value: "godaddy", label: "GoDaddy" },
  { value: "squarespace", label: "Squarespace" },
  { value: "wix", label: "Wix" },
  { value: "namecheap", label: "Namecheap" },
  { value: "other", label: "Other" },
];

const GodaddyInstructions = () => {
  return (
    <div className="provider-instructions">
      <h4>Share domain name access - Godaddy</h4>
      <p>
        Please grant us delegate access to your domain name on Godaddy so that
        we can quickly transfer your website to your custom domain name. To do
        so:
      </p>
      <ol>
        <li>
          Go to your{" "}
          <a href="https://account.godaddy.com/access" target="_blank">
            GoDaddy Delegate Access page
          </a>
          . You might be prompted to sign in.
        </li>
        <li>
          In the <strong>People who can access my account</strong> section,
          select <strong>Invite to Access</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/godaddy-invite-to-access.png"></img>
        </li>
        <li>
          Enter <strong>MioCommerce</strong> for the name field and{" "}
          <strong>websitethemes@miocommerce.com</strong> for the email field.
        </li>
        <li>
          Select at least <strong>Domains Only</strong> for the permission
        </li>
        <li>
          Click on <strong>Invite</strong>
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/godaddy-send-invite.png"></img>
        </li>
        <li>
          Once done, click on <strong>Submit</strong> below.
        </li>
      </ol>
    </div>
  );
};

const SquarespaceInstructions = () => {
  return (
    <div className="provider-instructions">
      <h4>Share domain name access - Squarespace</h4>
      <p>
        Please invite us as a domain manager on Squarespace so that we can
        quickly transfer your website to your custom domain name. To do so:
      </p>
      <ol>
        <li>
          Login to your Squarespace account and go to your{" "}
          <a href="https://account.squarespace.com/domains" target="_blank">
            domains page
          </a>
          .
        </li>
        <li>
          Select the domain you want to use for your website from the list.
        </li>
        <li>
          Click on <strong>Permissions</strong> in the left sidebar and click on{" "}
          <strong>Invite domain manager</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/squarespace-invite.png"></img>
        </li>
        <li>
          Enter <strong>MioCommerce</strong> for the name field and{" "}
          <strong>websitethemes@miocommerce.com</strong> for the email field.
        </li>
        <li>
          Click on <strong>Invite</strong>
          <img
            style={{ maxWidth: 400 }}
            src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/squarespace-send-invite.png"
          ></img>
        </li>
        <li>
          Once done, click on <strong>Submit</strong> below.
        </li>
      </ol>
    </div>
  );
};

const WixInstructions = () => {
  return (
    <div className="provider-instructions">
      <h4>Share domain name access - Wix</h4>
      <p>
        Please invite us as a domain manager on Wix so that we can quickly
        transfer your website to your custom domain name. To do so:
      </p>
      <ol>
        <li>
          Log in to your Wix website and go to <strong>Settings</strong>.
        </li>
        <li>
          Under <strong>General</strong> click on{" "}
          <strong>Roles & Permissions</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/wix-settings-page.png"></img>
        </li>
        <li>
          Click on <strong>Invite Collaborators</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/wix-invite-collaborators.png"></img>
        </li>
        <li>
          In the text box, enter <strong>websitethemes@miocommerce.com</strong>.
        </li>
        <li>
          In the permissions options, tick the box for{" "}
          <strong>Domain Manager</strong>.
        </li>
        <li>
          Click on <strong>Send Invite</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/wix-send-invite.png"></img>
        </li>
        <li>
          Once done, click on <strong>Submit</strong> below.
        </li>
      </ol>
    </div>
  );
};

const NamecheapInstructions = () => {
  return (
    <div className="provider-instructions">
      <h4>Share domain name access - Namecheap</h4>
      <p>
        Please invite us as a domain manager on Namecheap so that we can quickly
        transfer your website to your custom domain name. To do so:
      </p>
      <ol>
        <li>
          Log in to your Namecheap account and go to{" "}
          <strong>Domain List</strong>.
        </li>
        <li>
          Select the domain you want to use for your website and click on{" "}
          <strong>Manage</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/namecheap-domains-list.png"></img>
        </li>
        <li>
          Click on <strong>Sharing & Transfer</strong> and enter{" "}
          <strong>websitethemes@miocommerce.com</strong> in the{" "}
          <strong>New Manager</strong> text box under{" "}
          <strong>Share Access</strong>. Click on <strong>Add</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/namecheap-share-access.png"></img>
        </li>
        <li>
          Select <strong>Give manager full access</strong> in the dropdown and
          click on <strong>Confirm</strong>.
          <img src="https://themesondemand.b-cdn.net/MioCommerce/Olympus/dns-instructions/namecheap-permissions.png"></img>
        </li>
        <li>
          Once done, click on <strong>Submit</strong> below.
        </li>
      </ol>
    </div>
  );
};

const OtherInstructions = () => {
  return (
    <div className="provider-instructions">
      <h4>Other domain provider</h4>
      <p>
        If your domain provider allows for sharing access to your account,
        please invite our email <strong>websitethemes@miocommerce.com</strong>
        to access your account so that we can quickly transfer your website to
        your custom domain.
      </p>
    </div>
  );
};

const PROVIDER_INSTRUCTIONS = {
  godaddy: GodaddyInstructions,
  squarespace: SquarespaceInstructions,
  wix: WixInstructions,
  namecheap: NamecheapInstructions,
  other: OtherInstructions,
};

const SuccessMessage = () => (
  <div className="domain-form-success">
    <h3>Thank you for submitting your custom domain information!</h3>
    <p>
      We have received your domain information. We will get back to you within
      24 business hours to finish transferring your website to your custom
      domain.
    </p>
  </div>
);

const DomainForm = () => {
  const [formData, setFormData] = useState({
    hasDomain: null,
    domain: "",
    provider: "",
    wantsHelp: true,
    instructionStatus: null,
    desiredDomain: "",
    purchaseOption: null,
    hasPurchasedDomain: false,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const isFormSubmitted =
    window.live_app_data["form-connect-domaine-live-site"] === "true";

  useEffect(() => {
    if (isFormSubmitted) {
      setIsSubmitted(true);
    }
  }, [isFormSubmitted]);

  const handleDomainOptionChange = (hasDomain) => {
    setFormData((prev) => ({
      ...prev,
      hasDomain,
      domain: "",
      provider: "",
      purchaseOption: null,
      hasPurchasedDomain: false,
    }));
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  const handlePurchaseOptionChange = (option) => {
    setFormData((prev) => ({
      ...prev,
      purchaseOption: option,
      desiredDomain: "",
      hasPurchasedDomain: false,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setSubmitError(null);

    try {
      const response = await fetch(
        `${window.live_app_data.site_url}/wp-json/wb-onboard/v1/domain-connect`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        }
      );

      const data = await response.json();

      if (!response.ok) {
        throw new Error(
          data.data.errors ? data.data.errors.join(", ") : "An error occurred"
        );
      }

      setIsSubmitted(true);
      window.live_app_data["form-connect-domaine-live-site"] = "true";
    } catch (error) {
      setSubmitError(error.message);
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };
  // const handleInstructionStatusChange = (status) => {
  //   setFormData((prev) => ({
  //     ...prev,
  //     instructionStatus: prev.instructionStatus === status ? null : status,
  //   }));
  // };

  if (isSubmitted) {
    return <SuccessMessage />;
  }

  return (
    <form className="domain-form" onSubmit={handleSubmit}>
      <p>
        Your website went live on a MioCommerce domain ending in
        miocommerce-sites.com. To make your website accessible on your own
        company domain, follow the steps below. NOTE: The full domain transfer
        may take up to 24 business hours.
      </p>

      <div className="domain-form-group">
        <div className="domain-form-step">Step 1</div>
        <div
          className={`domain-form-radio ${
            formData.hasDomain === true ? "selected" : ""
          }`}
          onClick={() => handleDomainOptionChange(true)}
        >
          <input
            type="radio"
            name="hasDomain"
            checked={formData.hasDomain === true}
            onChange={() => {}}
          />
          <label>I already have a domain</label>
        </div>
        <div
          className={`domain-form-radio ${
            formData.hasDomain === false ? "selected" : ""
          }`}
          onClick={() => handleDomainOptionChange(false)}
        >
          <input
            type="radio"
            name="hasDomain"
            checked={formData.hasDomain === false}
            onChange={() => {}}
          />
          <label>I don't have a domain</label>
        </div>
      </div>

      {formData.hasDomain === true && (
        <>
          <div className="domain-form-step">Step 2</div>
          <div className="domain-form-input">
            <label htmlFor="domain">Domain name</label>
            <input
              type="text"
              id="domain"
              name="domain"
              value={formData.domain}
              onChange={handleInputChange}
              placeholder="example.com"
            />
          </div>

          <div className="domain-form-input">
            <label htmlFor="provider">Domain provider</label>
            <select
              id="provider"
              name="provider"
              value={formData.provider}
              onChange={handleInputChange}
            >
              <option value="">Select a provider</option>
              {DOMAIN_PROVIDERS.map((provider) => (
                <option key={provider.value} value={provider.value}>
                  {provider.label}
                </option>
              ))}
            </select>
          </div>

          {formData.provider && (
            <div className="domain-form-info">
              {React.createElement(PROVIDER_INSTRUCTIONS[formData.provider])}
            </div>
          )}
          {submitError && <div className="form-error">{submitError}</div>}

          <button
            type="submit"
            className="domain-form-submit"
            disabled={isSubmitting}
          >
            {isSubmitting ? "Sending..." : "Submit"}
          </button>
        </>
      )}

      {formData.hasDomain === false && (
        <>
          <div className="domain-form-info">
            <p>
              Having a custom domain is important for your brand to stand out.
              Domains can be purchased through domain registrars for a low
              yearly fee (20-50$ / year) or MioCommerce can manage your domain
              for you.
            </p>
          </div>

          <div className="domain-form-group">
            <div className="domain-form-step">Step 2</div>
            <div
              className={`domain-form-radio ${
                formData.purchaseOption === "mio" ? "selected" : ""
              }`}
              onClick={() => handlePurchaseOptionChange("mio")}
            >
              <input
                type="radio"
                name="purchaseOption"
                checked={formData.purchaseOption === "mio"}
                onChange={() => {}}
              />
              <label>I would like MioCommerce to purchase my domain</label>
            </div>
            <div
              className={`domain-form-radio ${
                formData.purchaseOption === "self" ? "selected" : ""
              }`}
              onClick={() => handlePurchaseOptionChange("self")}
            >
              <input
                type="radio"
                name="purchaseOption"
                checked={formData.purchaseOption === "self"}
                onChange={() => {}}
              />
              <label>I will purchase my domain myself</label>
            </div>
          </div>

          {formData.purchaseOption === "mio" && (
            <>
              <div className="domain-form-step">Step 3</div>
              <div className="domain-form-input">
                <label htmlFor="desiredDomain">
                  What domain would you like to use?
                </label>
                <span>
                  In case one is no longer available please provide at least two
                  options.
                </span>
                <input
                  type="text"
                  id="desiredDomain"
                  name="desiredDomain"
                  value={formData.desiredDomain}
                  onChange={handleInputChange}
                  placeholder="mydomain.com, mydomainalternative.com"
                  style={{ marginTop: 15 }}
                  required
                />
              </div>
              <p>
                We cannot guarantee that your selected domain will be available
                for purchase. We will search on domain registrars for your
                domain's availability and will contact you to confirm the
                purchase.
              </p>

              {submitError && <div className="form-error">{submitError}</div>}

              <button
                type="submit"
                className="domain-form-submit"
                disabled={isSubmitting || !formData.desiredDomain}
              >
                {isSubmitting ? "Sending..." : "Submit"}
              </button>
            </>
          )}

          {formData.purchaseOption === "self" && (
            <>
              <div className="domain-form-step">Step 3</div>
              <div className="domain-form-info">
                <p>
                  We recommend using Godaddy to purchase your domain, you can
                  follow these steps to do so:
                </p>
                <ol>
                  <li>
                    Visit{" "}
                    <a
                      href="https://www.godaddy.com"
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      godaddy.com
                    </a>
                  </li>
                  <li>Search for your desired domain name</li>
                  <li>Follow the purchase process</li>
                  <li>Once purchased, come back here to continue the setup</li>
                </ol>
              </div>

              <div className="domain-form-input">
                <label htmlFor="domain">What domain did you purchase?</label>
                <input
                  type="text"
                  id="domain"
                  name="domain"
                  value={formData.domain}
                  onChange={handleInputChange}
                  placeholder="mydomain.com"
                  required
                />
              </div>

              <div>{GodaddyInstructions()}</div>

              <div className="domain-form-checkbox">
                <label>
                  <input
                    type="checkbox"
                    name="hasPurchasedDomain"
                    checked={formData.hasPurchasedDomain}
                    onChange={handleInputChange}
                    required
                  />
                  I have purchased my domain and shared access with MioCommerce
                </label>
              </div>

              {submitError && <div className="form-error">{submitError}</div>}

              <button
                type="submit"
                className="domain-form-submit"
                disabled={
                  isSubmitting ||
                  !formData.hasPurchasedDomain ||
                  !formData.domain
                }
              >
                {isSubmitting ? "Sending..." : "Submit"}
              </button>
            </>
          )}
        </>
      )}
    </form>
  );
};

export default DomainForm;
