"use client";

import { useRouter } from "next/navigation";
import CopyBusinessIdButton from "@/components/CopyBusinessIdButton";
import InstagramConnectionDialogs from "@/components/InstagramConnectionDialogs";
import { useAppSelector } from "@/hooks/useAppDispatch";
import { useInstagramDisconnect } from "@/hooks/useInstagramDisconnect";
import { useInstagramConnectionFlow } from "@/hooks/useInstagramConnectionFlow";
import {
  buildMetaPartnerAccessUrl,
  getMetaPartnerBusinessId,
} from "@/lib/instagramAuth";
import {
  AlertTriangle,
  CheckCircle,
  Link as LinkIcon,
  Lock,
  Shield,
} from "react-feather";
import config from "@/utils/config";

export default function MediaBoostSetupAndConnectionsPage() {
  const router = useRouter();
  const businessId = getMetaPartnerBusinessId();
  const instagramLogoSrc = `${config.ENV_VARS.CDN_URL}/images/influential/Instagram.webp`;
  const metaAccessSrc = `${config.ENV_VARS.CDN_URL}/images/influential/media-boost/media-boost-img1.jpg`;
  const username = useAppSelector((state) => state.autoDm.username);
  const { disconnectInstagram, isDisconnecting } = useInstagramDisconnect();
  const {
    connected,
    connectUrl,
    connectionIssue,
    dismissConnectionIssue,
    openPermissionsModal,
    closePermissionsModal,
    modalSource,
    reconnectInstagram,
    showLoader,
    showPermissions,
  } = useInstagramConnectionFlow({
    flow: "media-boost",
    sessionStorageKey: "mediaBoostProcessedCode",
    returnToPath: "/media-boost/setup-and-connections",
  });

  const handleConnectInstagram = () => {
    if (connected) {
      void disconnectInstagram();
      return;
    }

    openPermissionsModal("cta");
  };

  const handleProvideMetaAccess = () => {
    if (typeof window !== "undefined") {
      window.location.href = buildMetaPartnerAccessUrl();
    }
  };

  const handleSubmitAdCode = () => {
    router.push("/media-boost/submit-ad-code");
  };

  if (showLoader) {
    return (
      <div className="pcoded-main-container">
        <div className="pcoded-content text-center py-20">
          <div className="d-flex flex-column align-items-center justify-content-center">
            <div
              className="spinner-border mb-3"
              style={{ width: "3rem", height: "3rem", color: "#C600BA" }}
              role="status"
            >
              <span className="visually-hidden">Loading...</span>
            </div>
            <h4 className="mb-2">Checking Instagram Connection</h4>
            <p className="text-muted mb-0">
              Please wait while we verify your connection...
            </p>
          </div>
        </div>
      </div>
    );
  }

  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">Get Started with Media Boost</h3>
            <p className="text-md color-content mb-2">Connect your accounts to start boosting your content and tracking performance</p>
            <div className="bg-color-yellow-light border rounded-3 px-md-3 p-2 mb-3">
              <p className="text-sm color-black m-0">
                <span className="text-sm fw-600 color-black m-0">Influential.com</span> will run ads using its own ad spend. Media costs will be deducted before revenue share.
              </p>
            </div>
          </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-8 col-xl-8 col-lg-7 col-md-12 col-sm-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-0">
                      <img
                        src={instagramLogoSrc}
                        alt="Instagram svg"
                        className="w-40 h-40 m-0"
                      />
                      <div>
                        <h3 className="text-lg color-content fw-600 mb-0">Step 1: Connect Instagram</h3>
                        <p className="text-sm mb-0">Connect your Instagram account to enable Auto-DM, analytics tracking, and post mapping.</p>
                      </div>
                    </div>

                    {connected && username ? (
                      <div className="d-flex flex-column flex-md-row align-items-md-center gap-3 mt-3 mb-3">
                        <div className="platform-card links-ulr-card px-0 py-1 card mb-0">
                          <div className="card-body p-0 w-100">
                            <div className="url-logo-area d-flex mb-0 w-100">
                              <img
                                src={instagramLogoSrc}
                                alt="Instagram logo"
                                className="url-logo-input"
                              />
                              <input
                                type="text"
                                className="form-control w-100"
                                value={username}
                                readOnly
                                aria-label="Connected Instagram username"
                              />
                            </div>
                          </div>
                        </div>

                        <button
                          type="button"
                          className="button-style btn-outline-second w-fit-content h-40 px-3"
                          onClick={handleConnectInstagram}
                          disabled={isDisconnecting}
                        >
                          {isDisconnecting ? "Disconnecting..." : "Disconnect Instagram"}
                        </button>
                      </div>
                    ) : (
                      <button
                        type="button"
                        className="button-style btn-outline-first but-w h-40 px-3 my-3 my-md-4"
                        onClick={handleConnectInstagram}
                        disabled={isDisconnecting}
                      >
                        <LinkIcon className="feather feather-link iconSize-18" /> {isDisconnecting ? "Disconnecting..." : "Connect Instagram"}
                      </button>
                    )}

                    <p
                      className="text-primary text-decoration-underline mb-3"
                      style={{ cursor: "pointer", fontSize: "12px" }}
                      onClick={() => openPermissionsModal("info")}
                    >
                      Why are these permissions required?
                    </p>

                    <ul className="d-flex justify-content-start align-items-center gap-2 gap-xl-3 p-0 mb-0">
                      <li className="text-sm d-flex justify-content-start align-items-start gap-2 mb-0">
                        <CheckCircle className="feather feather-check-circle iconSize-16" style={{ stroke: "var(--success)" }} />
                        You keep content ownership
                      </li>
                      <li className="text-sm d-flex justify-content-start align-items-start gap-2 mb-0">
                        <CheckCircle className="feather feather-check-circle iconSize-16" style={{ stroke: "var(--success)" }} />
                        You can revoke access anytime
                      </li>
                      <li className="text-sm d-flex justify-content-start align-items-start gap-2 mb-0">
                        <CheckCircle className="feather feather-check-circle iconSize-16" style={{ stroke: "var(--success)" }} />
                        We only use access for campaigns and analytics
                      </li>
                    </ul>
                  </div>
                </div>

                <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">
                      <Shield className="iconSize-40 svg-stroke-white-same rounded-2 bg-color-first p-2" />

                      <div className="d-md-flex justify-content-between align-items-start gap-2 gap-md-3 w-100">
                        <div className="mb-2 mb-md-0">
                          <h3 className="text-lg color-content fw-600 mb-0">Step 2: Provide Meta Access &amp; Assign Assets</h3>
                          <p className="text-sm mb-0">To launch paid campaigns on your posts, you must grant full access to your Meta Business Manager assets.</p>
                        </div>

                        <div className="text-sm w-fit-content fw-500 bg-color-red-light border rounded-5 d-flex justify-content-center align-items-center gap-1 min-w-fit-content py-1 px-2 m-0">
                          <LinkIcon className="feather feather-link bg-color-red rounded-5 stroke-white status-icons p-3px m-0" />
                          Not connected
                        </div>
                      </div>
                    </div>

                    <div className="d-flex justify-content-between align-items-center gap-2 bg-color-light3 border rounded-3 px-md-3 p-2 mb-3">
                      <div>
                        <p className="text-sm color-black m-0">Business ID:</p>
                        <p className="text-md fw-600 color-black m-0">{businessId}</p>
                      </div>

                      <CopyBusinessIdButton businessId={businessId} />
                    </div>

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

                      <ol className="list ps-3 mb-0">
                        <li className="mb-2">Open Meta Business Manager</li>
                        <li className="mb-2">Go to Business <span className="fw-600 color-black m-0">Settings → Partners</span></li>
                        <li className="mb-2">Click <span className="fw-600 color-black m-0">Add Partner → Give a Partner Access to Your Assets</span><br />• Enter Business ID: <span className="fw-600 color-black m-0">{businessId}</span></li>
                        <li className="mb-2">Under <span className="fw-600 color-black m-0">Facebook Pages</span>, select your Facebook Page and enable <span className="fw-600 color-black m-0">Full Control</span></li>
                        <li className="mb-2">Under <span className="fw-600 color-black m-0">Instagram Accounts</span>, select your connected Instagram account and enable <span className="fw-600 color-black m-0">Full Control</span></li>
                        <li className="mb-0">Click <span className="fw-600 color-black m-0">Assign Assets</span></li>
                      </ol>
                    </div>

                    <img
                      className="w-100 rounded-3 border mb-3 mt-0"
                      src={metaAccessSrc}
                      alt="Meta access instructions"
                    />

                    <button type="button" className="button-style btn-first but-w h-40 px-4 m-0" onClick={handleProvideMetaAccess}>Provide Meta Access</button>
                  </div>
                </div>

                <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-3">
                      <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="button" className="button-style btn-first but-w h-40 px-4 m-0" onClick={handleSubmitAdCode}>Submit Ad Code</button>
                  </div>
                </div>
              </div>

              <div className="col-xxl-4 col-xl-4 col-lg-5 col-md-12 col-12">
                <div className="card bg-second border-0 shadow-none rounded-4 m-0">
                  <div className="card-body p-4">
                    <h3 className="smallHeading color-content fw-600 mb-3">What Happens After Setup?</h3>
                    <ul className="list ps-3 mb-0">
                      <li className="mb-2">Influential.com selects posts eligible for boosting</li>
                      <li className="mb-2">Campaigns are launched using Influential.com&apos;s ad spend</li>
                      <li className="mb-2">Performance is tracked via Meta API</li>
                      <li className="mb-2">Ad spend is deducted</li>
                      <li className="mb-2">Net revenue is shared</li>
                      <li className="mb-0">Earnings are visible in your dashboard</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <InstagramConnectionDialogs
          connectUrl={connectUrl}
          connectionIssue={connectionIssue}
          isPermissionsOpen={showPermissions}
          onCloseIssue={dismissConnectionIssue}
          onClosePermissions={closePermissionsModal}
          onReconnect={reconnectInstagram}
          permissionsSource={modalSource}
        />
      </div>
    </div>
  );
}