import { useQuery } from "@tanstack/react-query";
import { wpApi } from "../api/wp-api";
import { toast } from "react-toastify";
import type { ConnectionInfo } from "../types/settings";
import { usePlan } from "../hooks/usePlan";
import { useWorkspace } from "../hooks/useWorkspace";
import { viralySsoUrl } from "../utils/sso";

const PLAN_FEATURES: Record<string, string[]> = {
  Free: ["3 social profiles", "10 posts/month", "Basic analytics"],
  Influencer: ["5 social profiles", "200 posts/month", "6-month analytics"],
  Business: ["15 social profiles", "500 posts/month", "12-month analytics", "5 team members"],
  Agency: ["50 social profiles", "Unlimited posts", "60-month analytics", "15 team members"],
  Enterprise: ["100 social profiles", "Unlimited posts", "Unlimited analytics", "15 team members"],
};

export default function Settings() {
  const { plan } = usePlan();
  const { workspaceName } = useWorkspace();
  const { data: connection, isLoading } = useQuery({
    queryKey: ["connection"],
    queryFn: () => wpApi.get<ConnectionInfo>("connection"),
  });

  const handleDisconnect = async () => {
    if (!confirm("Disconnect this site from Viraly?\n\nYou can reconnect at any time.")) return;
    try {
      await wpApi.post("disconnect", {});
      toast.success("Disconnected. Reloading...");
      setTimeout(() => window.location.reload(), 1000);
    } catch {
      toast.error("Failed to disconnect.");
    }
  };

  const features = plan ? (PLAN_FEATURES[plan.plan] || PLAN_FEATURES.Free) : [];

  return (
    <div className="vr-space-y-5">
      {/* Connection & Workspace */}
      <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-7">
        <div className="vr-mb-4">
          <h2 className="vr-text-base vr-font-bold vr-text-gray-900">Connection</h2>
          <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">Your WordPress site's connection to Viraly.</p>
        </div>

        {isLoading ? (
          <div className="vr-flex vr-items-center vr-gap-2 vr-py-4 vr-text-gray-400 vr-text-sm">
            <div className="vr-w-4 vr-h-4 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
            Loading...
          </div>
        ) : (
          <>
            <div className="vr-bg-gray-50 vr-rounded-lg vr-border vr-border-gray-200 vr-divide-y vr-divide-gray-200 vr-mb-5">
              <div className="vr-flex vr-justify-between vr-items-center vr-px-4 vr-py-3">
                <span className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wide">Status</span>
                <span className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-2.5 vr-py-0.5 vr-rounded-full vr-text-xs vr-font-semibold vr-bg-emerald-50 vr-text-emerald-600">
                  <span className="vr-w-1.5 vr-h-1.5 vr-rounded-full vr-bg-emerald-500" />
                  Connected
                </span>
              </div>
              <div className="vr-flex vr-justify-between vr-items-center vr-px-4 vr-py-3">
                <span className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wide">Site</span>
                <span className="vr-text-xs vr-text-gray-700">{connection?.siteUrl || viralyWP.siteUrl}</span>
              </div>
              {workspaceName && (
                <div className="vr-flex vr-justify-between vr-items-center vr-px-4 vr-py-3">
                  <span className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wide">Workspace</span>
                  <span className="vr-text-xs vr-font-medium vr-text-gray-700">{workspaceName}</span>
                </div>
              )}
            </div>

            <div className="vr-flex vr-gap-3">
              <a
                href={viralyWP.connectUrl}
                className="vr-inline-flex vr-items-center vr-gap-2 vr-px-4 vr-py-2 vr-bg-gray-100 vr-text-gray-700 vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-gray-200 vr-transition-colors"
              >
                <i className="fa-solid fa-arrows-rotate" style={{ fontSize: "10px" }} />
                Reconnect
              </a>
              <button
                onClick={handleDisconnect}
                className="vr-inline-flex vr-items-center vr-gap-2 vr-px-4 vr-py-2 vr-text-red-500 vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-red-50 vr-transition-colors vr-border-0 vr-bg-transparent vr-cursor-pointer"
              >
                <i className="fa-solid fa-xmark" style={{ fontSize: "10px" }} />
                Disconnect
              </button>
            </div>
          </>
        )}
      </div>

      {/* Plan */}
      {plan && (
        <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-7">
          <div className="vr-flex vr-items-start vr-justify-between vr-mb-4">
            <div>
              <h2 className="vr-text-base vr-font-bold vr-text-gray-900">Your Plan</h2>
              <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">
                You're on the <span className="vr-font-semibold vr-text-gray-700">{plan.plan}</span> plan
              </p>
            </div>
            <a
              href={viralySsoUrl("/settings/subscription")}
              target="_blank"
              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-md vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors"
            >
              <i className="fa-solid fa-bolt" style={{ fontSize: "10px" }} />
              {plan.plan === "Free" ? "Upgrade" : "Manage Plan"}
            </a>
          </div>

          <div className="vr-grid vr-grid-cols-2 sm:vr-grid-cols-4 vr-gap-3 vr-mb-4">
            <div className="vr-text-center vr-py-3 vr-bg-gray-50 vr-rounded-lg">
              <p className="vr-text-lg vr-font-bold vr-text-gray-900">{plan.channelsUsed}</p>
              <p className="vr-text-xs vr-text-gray-400">of {plan.channelsLimit} profiles</p>
            </div>
            <div className="vr-text-center vr-py-3 vr-bg-gray-50 vr-rounded-lg">
              <p className="vr-text-lg vr-font-bold vr-text-gray-900">{plan.channelsLocked}</p>
              <p className="vr-text-xs vr-text-gray-400">locked</p>
            </div>
            <div className="vr-col-span-2 vr-py-3 vr-px-4 vr-bg-gray-50 vr-rounded-lg">
              <p className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wide vr-mb-1.5">Includes</p>
              <div className="vr-flex vr-flex-wrap vr-gap-1.5">
                {features.map((f) => (
                  <span key={f} className="vr-text-xs vr-text-gray-600 vr-bg-white vr-px-2 vr-py-0.5 vr-rounded-md vr-border vr-border-gray-200">
                    {f}
                  </span>
                ))}
              </div>
            </div>
          </div>

          {plan.plan === "Free" && (
            <div className="vr-p-3 vr-rounded-lg vr-bg-primary-50 vr-border vr-border-primary-200">
              <p className="vr-text-xs vr-text-primary-700">
                <strong>Upgrade to unlock</strong> more profiles, unlimited posts, AI captions, advanced analytics, and team collaboration.
              </p>
            </div>
          )}
        </div>
      )}

      {/* Links */}
      <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-5">
        <div className="vr-flex vr-flex-wrap vr-gap-4 vr-justify-center">
          <a href={viralySsoUrl("/settings")} target="_blank" className="vr-text-xs vr-text-gray-500 hover:vr-text-primary-600 vr-transition-colors">
            Viraly Settings →
          </a>
          <a href="https://viraly.io/support" target="_blank" className="vr-text-xs vr-text-gray-500 hover:vr-text-primary-600 vr-transition-colors">
            Support →
          </a>
          <a href="https://viraly.io" target="_blank" className="vr-text-xs vr-text-gray-500 hover:vr-text-primary-600 vr-transition-colors">
            Viraly.io →
          </a>
        </div>
      </div>
    </div>
  );
}
