import { useEffect, useState, useCallback } 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, refresh } = useChannels();
  const { defaultSocialSetId } = useSocialSets();
  const { plan } = usePlan();
  const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
  const [subTab, setSubTab] = useState<SubTab>(channels.length > 0 ? "manage" : "connect");

  // When channels load for the first time, default to manage if they have profiles
  useEffect(() => {
    if (!channelsLoading && channels.length > 0 && subTab === "connect") {
      // Only auto-switch on initial load, not after user interaction
    }
  }, [channelsLoading]);

  // Listen for channel changes from OAuth popup — switch to Manage tab to show new profile
  const handleChannelsChanged = useCallback(() => {
    refresh();
    setSubTab("manage");
  }, [refresh]);

  useEffect(() => {
    window.addEventListener("viraly:channels-changed", handleChannelsChanged);
    return () => window.removeEventListener("viraly:channels-changed", handleChannelsChanged);
  }, [handleChannelsChanged]);

  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>
              ) : 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>
  );
}
