import { useEffect, useState, useCallback, useRef } from "react";
import { useChannels } from "../hooks/useChannels";
import { useSocialSets } from "../hooks/useSocialSets";
import { usePlan } from "../hooks/usePlan";
import { wpApi } from "../api/wp-api";
import { toast } from "react-toastify";
import clsx from "clsx";
import ChannelCard from "../components/ChannelCard";
import QuotaBar from "../components/QuotaBar";
import PlatformGrid from "../components/PlatformGrid";

type SubTab = "connect" | "manage";

export default function SocialProfiles() {
  const { channels, isLoading: channelsLoading, error: channelsError, refresh } = useChannels();
  const { defaultSocialSetId } = useSocialSets();
  const { plan } = usePlan();
  const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
  const [subTab, setSubTabState] = useState<SubTab>("connect");
  const hasUserInteracted = useRef(false);
  const hasAutoSwitched = useRef(false);

  const setSubTab = (tab: SubTab) => {
    hasUserInteracted.current = true;
    setSubTabState(tab);
  };

  // On first render the channels query has not resolved, so the initial state
  // cannot know whether the user has profiles. Once loading finishes, land
  // returning users on Manage - unless they already clicked a tab themselves.
  useEffect(() => {
    if (!channelsLoading && !hasAutoSwitched.current) {
      hasAutoSwitched.current = true;
      if (channels.length > 0 && !hasUserInteracted.current) {
        setSubTabState("manage");
      }
    }
  }, [channelsLoading, channels.length]);

  // A SUCCESSFUL connect switches to Manage to show the new profile; plain
  // channels-changed refetches (popup closed, errors) must not yank the user
  // off the Connect tab.
  const handleOAuthComplete = useCallback(() => {
    refresh();
    setSubTabState("manage");
  }, [refresh]);

  useEffect(() => {
    window.addEventListener("viraly:oauth-complete", handleOAuthComplete);
    return () => window.removeEventListener("viraly:oauth-complete", handleOAuthComplete);
  }, [handleOAuthComplete]);

  const handleDisconnect = async (id: string, name: string) => {
    if (!confirm(`Disconnect "${name}"?\n\nThis will remove the social account from Viraly. You can reconnect it at any time.`)) {
      return;
    }

    setDisconnectingId(id);
    try {
      await wpApi.del(`channels/${id}`);
      toast.success(`${name} disconnected successfully.`);
      refresh();
    } catch {
      toast.error("Failed to disconnect. Please try again.");
    } finally {
      setDisconnectingId(null);
    }
  };

  const atLimit = plan ? plan.channelsUsed >= plan.channelsLimit : false;
  const connectedCount = channels.length;

  return (
    <div className="vr-space-y-5">
      <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-overflow-hidden">
        {/* Header */}
        <div className="vr-p-6 vr-pb-0">
          <div className="vr-mb-4">
            <h2 className="vr-text-base vr-font-bold vr-text-gray-900">Social Profiles</h2>
            <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">
              Connect and manage your social media accounts.
            </p>
          </div>

          {/* Sub-tabs */}
          <div className="vr-flex vr-gap-1 vr-border-b vr-border-gray-200 vr--mx-6 vr-px-6">
            <button
              onClick={() => setSubTab("manage")}
              className={clsx(
                "vr-px-4 vr-py-2.5 vr-text-sm vr-font-medium vr-border-0 vr-bg-transparent vr-cursor-pointer vr-transition-colors vr-border-b-2 vr--mb-px",
                subTab === "manage"
                  ? "vr-border-primary-600 vr-text-primary-600"
                  : "vr-border-transparent vr-text-gray-500 hover:vr-text-gray-700"
              )}
            >
              Manage{connectedCount > 0 && ` (${connectedCount})`}
            </button>
            <button
              onClick={() => setSubTab("connect")}
              className={clsx(
                "vr-px-4 vr-py-2.5 vr-text-sm vr-font-medium vr-border-0 vr-bg-transparent vr-cursor-pointer vr-transition-colors vr-border-b-2 vr--mb-px",
                subTab === "connect"
                  ? "vr-border-primary-600 vr-text-primary-600"
                  : "vr-border-transparent vr-text-gray-500 hover:vr-text-gray-700"
              )}
            >
              <i className="fa-solid fa-plus vr-mr-1.5" style={{ fontSize: "10px" }} />
              Connect New
            </button>
          </div>
        </div>

        {/* Tab content */}
        <div className="vr-p-6">
          {/* Quota bar — visible on both tabs */}
          {plan && <div className="vr-mb-5"><QuotaBar plan={plan} /></div>}

          {subTab === "manage" && (
            <>
              {channelsLoading ? (
                <div className="vr-flex vr-items-center vr-justify-center vr-gap-3 vr-py-10 vr-text-gray-400 vr-text-sm">
                  <div className="vr-w-5 vr-h-5 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
                  Loading profiles...
                </div>
              ) : channelsError ? (
                <div className="vr-text-center vr-py-10" role="alert">
                  <i className="fa-solid fa-triangle-exclamation vr-text-3xl vr-text-amber-300 vr-mb-3" />
                  <h3 className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-mb-1">Could not reach Viraly</h3>
                  <p className="vr-text-xs vr-text-gray-500 vr-mb-3">
                    Your profiles could not be loaded. This is a connection problem, not an empty account.
                  </p>
                  <button
                    onClick={() => refresh()}
                    className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-primary-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors vr-border-0 vr-cursor-pointer"
                  >
                    <i className="fa-solid fa-rotate-right" style={{ fontSize: "10px" }} />
                    Retry
                  </button>
                </div>
              ) : connectedCount > 0 ? (
                <div className="vr-grid vr-grid-cols-1 sm:vr-grid-cols-2 vr-gap-3">
                  {channels.map((ch) => (
                    <ChannelCard
                      key={ch.id}
                      channel={ch}
                      onDisconnect={handleDisconnect}
                      disconnecting={disconnectingId === ch.id}
                    />
                  ))}
                </div>
              ) : (
                <div className="vr-text-center vr-py-10">
                  <i className="fa-solid fa-users vr-text-3xl vr-text-gray-200 vr-mb-3" />
                  <h3 className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-mb-1">No profiles connected yet</h3>
                  <p className="vr-text-xs vr-text-gray-500 vr-mb-3">Connect your first social profile to get started.</p>
                  <button
                    onClick={() => setSubTab("connect")}
                    className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-primary-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors vr-border-0 vr-cursor-pointer"
                  >
                    <i className="fa-solid fa-plus" style={{ fontSize: "10px" }} />
                    Connect Profile
                  </button>
                </div>
              )}
            </>
          )}

          {subTab === "connect" && (
            <PlatformGrid
              defaultSocialSetId={defaultSocialSetId}
              disabled={atLimit}
              hasChannels={connectedCount > 0}
            />
          )}
        </div>
      </div>
    </div>
  );
}
