"use client";

import { useEffect, useState } from "react";
import { AlertTriangle, FileText, Lock, X, Check } from "react-feather";
import apiClient from "@/lib/apiClient";
import { logger } from "@/lib/logger";
import { validateAndNormalizeInstagramUrl, validatePartnershipAdCode } from "@/utils/instagramValidator";

type AlertType = "success" | "error" | "warning";

type StatusAlert = {
  id: string;
  type: AlertType;
  title?: string;
  message: string;
};

export default function SubmitAdCodePage() {
  const mdBreakpoint = 768;
  const [isBelowMd, setIsBelowMd] = useState(false);
  const [statusAlert, setStatusAlert] = useState<StatusAlert | null>(null);
  const [igPostUrl, setIgPostUrl] = useState("");
  const [partnershipAdCode, setPartnershipAdCode] = useState("");
  const [urlError, setUrlError] = useState<string | null>(null);
  const [codeError, setCodeError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [touched, setTouched] = useState({ url: false, code: false });

  useEffect(() => {
    const checkWidth = () => {
      setIsBelowMd(window.innerWidth < mdBreakpoint);
    };

    checkWidth();
    window.addEventListener("resize", checkWidth);

    return () => window.removeEventListener("resize", checkWidth);
  }, []);

  const handleDismissAlert = () => {
    const confirmed = window.confirm("Are you sure you want to dismiss this message?");

    if (!confirmed) return;

    setStatusAlert(null);
  };

  const showStatusAlert = (type: AlertType, message: string, title?: string) => {
    setStatusAlert({
      id: `${type}-${Date.now()}`,
      type,
      title,
      message,
    });
  };

  const validateUrl = (url: string) => {
    if (!url.trim()) {
      setUrlError("Instagram post URL is required");
      return false;
    }

    const validation = validateAndNormalizeInstagramUrl(url);
    if (!validation.valid) {
      setUrlError(validation.error || "Invalid Instagram URL");
      return false;
    }

    setUrlError(null);
    return true;
  };

  const validateCode = (code: string) => {
    const validation = validatePartnershipAdCode(code);
    if (!validation.valid) {
      setCodeError(validation.error || "Invalid partnership ad code");
      return false;
    }

    setCodeError(null);
    return true;
  };

  const handleUrlBlur = () => {
    setTouched((prev) => ({ ...prev, url: true }));
    validateUrl(igPostUrl);
  };

  const handleCodeBlur = () => {
    setTouched((prev) => ({ ...prev, code: true }));
    validateCode(partnershipAdCode);
  };

  const handleUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setIgPostUrl(e.target.value);
    if (touched.url) {
      validateUrl(e.target.value);
    }
  };

  const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPartnershipAdCode(e.target.value);
    if (touched.code) {
      validateCode(e.target.value);
    }
  };

  const handleSubmit = async () => {
    // Mark as touched
    setTouched({ url: true, code: true });

    // Validate both fields
    const urlValid = validateUrl(igPostUrl);
    const codeValid = validateCode(partnershipAdCode);

    if (!urlValid || !codeValid) {
      return;
    }

    // Get normalized URL with shortcode
    const validation = validateAndNormalizeInstagramUrl(igPostUrl);
    if (!validation.valid || !validation.normalizedUrl) {
      showStatusAlert("error", "Failed to process Instagram URL");
      return;
    }

    setIsSubmitting(true);
    setStatusAlert(null);

    try {
      await apiClient.post("/ig/posts/partner-posts/ad-codes", {
        ig_post_url: validation.normalizedUrl, // Send normalized URL
        partnership_ad_code: partnershipAdCode.trim(),
      });

      setIgPostUrl("");
      setPartnershipAdCode("");
      setUrlError(null);
      setCodeError(null);
      setTouched({ url: false, code: false });
      showStatusAlert(
        "success",
        "Your post will be reviewed and added to campaigns shortly.",
        "Ad Code Submitted successfully!"
      );
    } catch (error: any) {
      logger.error("Failed to submit ad code", error);
      const message =
        error?.response?.data?.description ||
        error?.response?.data?.message ||
        "Unable to submit the ad code right now. Please try again later.";
      showStatusAlert("error", message);
    } finally {
      setIsSubmitting(false);
    }
  };

  const getAlertConfig = (type: AlertType) => {
    switch (type) {
      case "success":
        return {
          wrapperClass: "d-flex justify-content-between align-items-md-center align-items-start gap-2 rounded-3 bg-color-green-light border border-green p-2 mb-0",
          titleClass: "text-sm color-green fw-500 mb-0",
          icon: <Check className="feather feather-check bg-success rounded-5 stroke-white status-icons iconSize-20 m-0" />,
        };
      case "warning":
        return {
          wrapperClass: "d-flex justify-content-between align-items-md-center align-items-start gap-2 rounded-3 bg-color-yellow-light border p-2 mb-0",
          titleClass: "text-sm fw-500 mb-0 color-yellow",
          icon: <AlertTriangle className="iconSize-20 flex-shrink-0" color="#FF7D09" />,
        };
      case "error":
      default:
        return {
          wrapperClass: "d-flex justify-content-between align-items-md-center align-items-start gap-2 rounded-3 bg-color-red-light border border-red p-2 mb-0",
          titleClass: "text-sm color-red fw-500 mb-0",
          icon: (
            <svg className="iconSize-20 svg-fill-red flex-shrink-0" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M8 32H31L20 10L8 32Z" fill="white" className="path-white"></path>
              <path d="M21.6667 23.3333H18.3333V15H21.6667M21.6667 30H18.3333V26.6666H21.6667M1.66666 35H38.3333L20 3.33331L1.66666 35Z" fill="#FF7D09"></path>
            </svg>
          ),
        };
    }
  };

  return (
    <div className="pcoded-main-container webContent">
      <div className="pcoded-content">
        <div className="row align-items-center align-items-md-end mb-md-0 mb-2">
          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 mt-3 text-md-start text-center">
            <h3 className="text-xl fw-500 mb-1">Submit Ad Code</h3>
            <p className="text-md color-content mb-3">Submit Partnership Ad Codes for posts you want us to boost.</p>
          </div>
        </div>

        <div className="row">
          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 mb-3">
            <div className="row g-3 mb-3">
              <div className="col-xxl-4 col-xl-4 col-lg-5 col-md-12 col-12 mb-lg-0 mb-3">
                <div className="card border shadow-none rounded-4 performance-card h-auto mb-3">
                  <div className="card-body platform-cards">
                    <div className="d-flex justify-content-start align-items-start gap-2 gap-md-3 mb-3">
                      <FileText className="iconSize-40 svg-stroke-white-same rounded-2 bg-color-first p-2" />

                      <div>
                        <h3 className="text-lg color-content fw-600 mb-0">Partnership Ad Code Form</h3>
                        <p className="text-sm mb-0">Each boosted post requires a unique ad code</p>
                      </div>
                    </div>

                    <p className="text-sm mb-3">Alternative (Only if you cannot provide full access)</p>

                    <form
                      id="submit-ad-code-form"
                      onSubmit={(event) => {
                        event.preventDefault();
                        handleSubmit();
                      }}
                    >
                      <div className="row g-3 profile-fields">
                        <div className="col-12">
                          <label className="text-sm color-content fw-600 mb-2">Instagram Post URL</label>
                          <input
                            type="text"
                            className={`form-control ${urlError && touched.url ? "border-danger" : ""}`}
                            value={igPostUrl}
                            onChange={handleUrlChange}
                            onBlur={handleUrlBlur}
                            disabled={isSubmitting}
                            placeholder="https://www.instagram.com/p/ABC123XYZ/..."
                          />
                          {urlError && touched.url && (
                            <div className="text-danger text-sm mt-2">
                              {urlError}
                            </div>
                          )}
                        </div>

                        <div className="col-12">
                          <label className="text-sm color-content fw-600 mb-2">Partnership Ad Code</label>
                          <input
                            type="text"
                            className={`form-control ${codeError && touched.code ? "border-danger" : ""}`}
                            value={partnershipAdCode}
                            onChange={handleCodeChange}
                            onBlur={handleCodeBlur}
                            disabled={isSubmitting}
                            placeholder="Enter the partnership ad code from Instagram"
                          />
                          {codeError && touched.code && (
                            <div className="text-danger text-sm mt-2">
                              {codeError}
                            </div>
                          )}
                        </div>

                        <div className="col-12">
                          <button
                            type="submit"
                            className="button-style btn-first h-40 px-4 m-0 w-100"
                            disabled={isSubmitting || (touched.url && urlError !== null) || (touched.code && codeError !== null)}
                          >
                            {isSubmitting ? "Submitting..." : "Submit Code"}
                          </button>
                        </div>
                      </div>
                    </form>

                    {statusAlert ? (
                      <div className="row g-2 pt-3">
                        <div className="col-12">
                          <div className={getAlertConfig(statusAlert.type).wrapperClass}>
                            {getAlertConfig(statusAlert.type).icon}
                            <div className="flex-grow-1">
                              <div className="text-start d-block text-sm color-content fw-500 mb-0">
                                {statusAlert.title ? <span className={getAlertConfig(statusAlert.type).titleClass}>{statusAlert.title}</span> : null}
                                {statusAlert.title ? " " : null}
                                {statusAlert.message}
                              </div>
                            </div>
                            <button type="button" className="no-bg-btn delete-platform m-0 p-0" onClick={handleDismissAlert}>
                              <X className="feather feather-x svg-stroke-black" />
                            </button>
                          </div>
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>

              </div>

              <div className="col-xxl-8 col-xl-8 col-lg-7 col-md-12 col-12">
                <div className="card border shadow-none rounded-4 performance-card h-auto mb-0">
                  <div className="card-body platform-cards">
                    <h3 className="text-lg color-content fw-600 mb-1">Manual Ad Code Submission (If Full Access Is Not Granted)</h3>
                    <p className="text-sm mb-3">Full access to Meta Business Manager is required to run paid campaigns. If you&apos;re unable to grant full Instagram access, you must generate and share a Partnership Ad Code for every post you want us to boost.</p>

                    <div className="bg-color-yellow-light border rounded-3 d-flex justify-content-start align-items-center gap-1 gap-md-2 px-md-3 p-2 mb-3">
                      <AlertTriangle className="iconSize-20" color="#FF7D09" />
                      <p className="text-sm color-black m-0"><strong className="text-sm color-black m-0">Important:</strong> If full Instagram access is not provided, an ad code is required for each individual post.</p>
                    </div>

                    <div className="bg-color-light rounded-3 p-3 mb-3">
                      <h3 className="text-lg color-content fw-600 mb-3">Step-by-Step Instructions</h3>

                      <ol className="ps-3 mb-0">
                        <li className="mb-2">Open the Reel you posted.</li>
                        <li className="mb-2">Go to the specific Reel you want us to boost.</li>
                        <li className="mb-2">Tap the three dots (⋯) in the top right corner.</li>
                        <li className="mb-2">Select "Partnership Label and Ads."</li>
                        <li className="mb-2">Toggle ON <span className="fw-600 color-black m-0">"Paid Partnership Label."</span></li>
                        <li className="mb-2">Add <span className="fw-600 color-black m-0">@influentialdotcom</span> as the brand partner.</li>
                        <li className="mb-2">Turn ON <span className="fw-600 color-black m-0">"Allow brand partner to boost."</span></li>
                        <li className="mb-2">Scroll to Partnership Ad Permissions.</li>
                        <li className="mb-2">Tap <span className="fw-600 color-black m-0">"Get Partnership Ad Code."</span></li>
                        <li className="mb-0">Copy and share the generated Ad Code with us.</li>
                      </ol>
                    </div>

                    <div className="d-flex justify-content-start align-items-center gap-1 gap-md-2 border rounded-3 p-3 mb-0">
                      <Lock className="feather feather-lock" />
                      <div>
                        <h3 className="text-sm color-content fw-600 mb-0">Compliance Reminder</h3>
                        <p className="text-sm mb-0">Make sure your caption includes #ad and the Paid Partnership label is enabled.</p>
                      </div>
                    </div>

                    <button
                      type="submit"
                      form="submit-ad-code-form"
                      disabled={isSubmitting}
                      className={`button-style btn-first but-w h-40 px-4 mt-3 m-0 ${isBelowMd ? "w-100" : ""}`}
                    >
                      {isSubmitting ? "Submitting..." : "Submit Ad Code"}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}