import { useChannels } from "../hooks/useChannels";
import { usePlan } from "../hooks/usePlan";
import { useWorkspace } from "../hooks/useWorkspace";
import { useQuery } from "@tanstack/react-query";
import { wpApi } from "../api/wp-api";
import { viralySsoUrl } from "../utils/sso";
import clsx from "clsx";

const PLATFORM_ICONS: Record<string, string> = {
  Facebook: "📘", Instagram: "📷", TikTok: "🎵", Twitter: "𝕏",
  LinkedIn: "💼", Pinterest: "📌", YouTube: "▶️", Threads: "🧵",
  Bluesky: "🦋", Mastodon: "🐘",
};

interface Props {
  onNavigate: (tab: string) => void;
}

export default function Dashboard({ onNavigate }: Props) {
  const { channels } = useChannels();
  const { plan } = usePlan();
  const { workspaceName } = useWorkspace();
  const activeChannels = channels.filter((ch) => ch.status === "Active");

  const { data: activity } = useQuery({
    queryKey: ["activity", 1],
    queryFn: () => wpApi.get<any>("activity?page=1"),
    staleTime: 60_000,
  });

  const recentActivity = activity?.items?.slice(0, 5) || [];
  const totalShared = activity?.total || 0;

  return (
    <div className="vr-space-y-5">
      {/* What do you want to do? */}
      <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-6">
        <div className="vr-flex vr-items-center vr-justify-between vr-mb-4">
          <div>
            <h2 className="vr-text-base vr-font-bold vr-text-gray-900">What do you want to do?</h2>
            {workspaceName && (
              <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">
                Workspace: <span className="vr-font-medium vr-text-gray-500">{workspaceName}</span>
              </p>
            )}
          </div>
          <div className="vr-flex vr-items-center vr-gap-2">
            {plan && (
              <a
                href={viralySsoUrl("/settings/subscription")}
                target="_blank"
                className={clsx(
                  "vr-inline-flex vr-items-center vr-gap-1.5 vr-px-3 vr-py-2 vr-rounded-lg vr-text-xs vr-font-semibold vr-transition-colors",
                  plan.plan === "Free"
                    ? "vr-bg-amber-50 vr-text-amber-700 hover:vr-bg-amber-100"
                    : "vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200"
                )}
              >
                {plan.plan === "Free" && <i className="fa-solid fa-bolt" style={{ fontSize: "10px" }} />}
                {plan.plan === "Free" ? "Upgrade" : `${plan.plan} Plan`}
              </a>
            )}
            <button
              onClick={() => onNavigate("profiles")}
              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" }} />
              Add Profile
            </button>
          </div>
        </div>
        <div className="vr-grid vr-grid-cols-3 vr-gap-3">
          {[
            { icon: "fa-solid fa-rotate", title: "Blog to Social", desc: "Share blog posts automatically", tab: "autopost" },
            { icon: "fa-solid fa-pen-to-square", title: "Scheduler", desc: "Compose, schedule & manage posts", tab: "scheduler" },
            { icon: "fa-solid fa-chart-line", title: "Analytics", desc: "View performance", tab: "analytics" },
          ].map((a) => (
            <button
              key={a.tab}
              onClick={() => onNavigate(a.tab)}
              className="vr-flex vr-flex-col vr-items-center vr-gap-2.5 vr-p-5 vr-bg-gray-50 vr-rounded-xl vr-transition-all hover:vr-bg-primary-50 hover:vr-shadow-sm vr-group vr-cursor-pointer vr-border-0"
            >
              <div className="vr-w-11 vr-h-11 vr-rounded-xl vr-flex vr-items-center vr-justify-center" style={{ background: "linear-gradient(135deg, #E03058, #c41d45)" }}>
                <i className={`${a.icon} vr-text-white`} style={{ fontSize: "15px" }} />
              </div>
              <div className="vr-text-center">
                <p className="vr-text-sm vr-font-semibold vr-text-gray-900 group-hover:vr-text-primary-600 vr-transition-colors">{a.title}</p>
                <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">{a.desc}</p>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Overview stats + profiles */}
      <div className="vr-grid vr-grid-cols-1 sm:vr-grid-cols-2 vr-gap-4">
        {/* Stats */}
        <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-5">
          <h3 className="vr-text-sm vr-font-bold vr-text-gray-900 vr-mb-3">Overview</h3>
          <div className="vr-grid vr-grid-cols-3 vr-gap-3">
            <div className="vr-text-center">
              <p className="vr-text-xl vr-font-bold vr-text-gray-900">{activeChannels.length}</p>
              <p className="vr-text-xs vr-text-gray-400">Profiles</p>
            </div>
            <div className="vr-text-center">
              <p className="vr-text-xl vr-font-bold vr-text-gray-900">{totalShared}</p>
              <p className="vr-text-xs vr-text-gray-400">Shared</p>
            </div>
            <div className="vr-text-center">
              <p className="vr-text-xl vr-font-bold vr-text-primary-600">{plan?.plan || "—"}</p>
              <p className="vr-text-xs vr-text-gray-400">Plan</p>
            </div>
          </div>
        </div>

        {/* Connected Profiles */}
        <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-items-center vr-justify-between vr-mb-3">
            <h3 className="vr-text-sm vr-font-bold vr-text-gray-900">Connected Profiles</h3>
            <button
              onClick={() => onNavigate("profiles")}
              className="vr-text-xs vr-font-semibold vr-text-primary-600 hover:vr-underline vr-border-0 vr-bg-transparent vr-cursor-pointer vr-p-0"
            >
              Manage →
            </button>
          </div>
          {activeChannels.length > 0 ? (
            <div className="vr-flex vr-items-center vr-gap-2 vr-flex-wrap">
              <div className="vr-flex vr--space-x-1.5">
                {activeChannels.slice(0, 6).map((ch) => (
                  <div key={ch.id} title={`${ch.name} (${ch.type})`}>
                    {ch.pictureUrl ? (
                      <img src={ch.pictureUrl} alt="" className="vr-w-8 vr-h-8 vr-rounded-full vr-border-2 vr-border-white vr-object-cover" />
                    ) : (
                      <span className="vr-w-8 vr-h-8 vr-rounded-full vr-border-2 vr-border-white vr-bg-gray-100 vr-flex vr-items-center vr-justify-center vr-text-xs">
                        {PLATFORM_ICONS[ch.type] || "🌐"}
                      </span>
                    )}
                  </div>
                ))}
                {activeChannels.length > 6 && (
                  <span className="vr-w-8 vr-h-8 vr-rounded-full vr-border-2 vr-border-white vr-bg-gray-200 vr-flex vr-items-center vr-justify-center vr-text-xs vr-font-bold vr-text-gray-500">
                    +{activeChannels.length - 6}
                  </span>
                )}
              </div>
              <span className="vr-text-xs vr-text-gray-400">{activeChannels.length} connected</span>
            </div>
          ) : (
            <button
              onClick={() => onNavigate("profiles")}
              className="vr-text-xs vr-text-primary-600 vr-font-semibold vr-border-0 vr-bg-transparent vr-cursor-pointer vr-p-0"
            >
              Connect your first profile →
            </button>
          )}
        </div>
      </div>

      {/* Plan overview — only for Free/Influencer */}
      {plan && (plan.plan === "Free" || plan.plan === "Influencer") && (
        <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-items-center vr-justify-between vr-mb-4">
            <h3 className="vr-text-sm vr-font-bold vr-text-gray-900">Your Plan</h3>
            <span className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wider vr-bg-gray-100 vr-px-2.5 vr-py-0.5 vr-rounded-full">
              {plan.plan}
            </span>
          </div>
          <div className="vr-grid vr-grid-cols-2 vr-gap-x-6 vr-gap-y-2">
            {/* What you have */}
            {plan.plan === "Free" ? (
              <>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>Up to 3 social profiles</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>10 posts per month</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>10 platforms supported</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>2 weeks analytics history</span>
                </div>
                {/* What you'd unlock */}
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>Unlimited posts</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>AI caption generator</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>Content recycling</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>6+ months analytics</span>
                </div>
              </>
            ) : (
              <>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>Up to 5 social profiles</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>200 posts per month</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>AI captions & hashtags</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-700">
                  <i className="fa-solid fa-check vr-text-emerald-500" style={{ fontSize: "10px" }} />
                  <span>6 months analytics</span>
                </div>
                {/* What you'd unlock */}
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>Up to 15 profiles</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>12 months analytics</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>Team collaboration</span>
                </div>
                <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-400">
                  <i className="fa-solid fa-lock" style={{ fontSize: "9px" }} />
                  <span>Priority support</span>
                </div>
              </>
            )}
          </div>
          <div className="vr-mt-4 vr-pt-3 vr-border-t vr-border-gray-100 vr-flex vr-items-center vr-justify-between">
            <span className="vr-text-xs vr-text-gray-500">
              {plan.plan === "Free" ? "Unlock more with Influencer" : "Unlock more with Business"}
            </span>
            <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-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors"
            >
              <i className="fa-solid fa-bolt" style={{ fontSize: "10px" }} />
              Upgrade
            </a>
          </div>
        </div>
      )}

      {/* Recent Activity */}
      {recentActivity.length > 0 && (
        <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-5">
          <h3 className="vr-text-sm vr-font-bold vr-text-gray-900 vr-mb-3">Recent Activity</h3>
          <div className="vr-space-y-2">
            {recentActivity.map((item: any) => (
              <div key={item.postId} className="vr-flex vr-items-center vr-gap-3 vr-text-xs vr-py-1.5">
                <span className={`vr-inline-flex vr-items-center vr-gap-1 vr-px-2 vr-py-0.5 vr-rounded-full vr-font-semibold vr-flex-shrink-0 ${
                  item.errorCount === 0
                    ? "vr-bg-emerald-50 vr-text-emerald-600"
                    : "vr-bg-red-50 vr-text-red-500"
                }`}>
                  {item.errorCount === 0 ? `✓ ${item.successCount}` : `✕ ${item.errorCount}`}
                </span>
                <span className="vr-text-gray-700 vr-truncate vr-flex-1">{item.title}</span>
                <div className="vr-flex vr-gap-0.5 vr-flex-shrink-0">
                  {item.channels?.slice(0, 4).map((ch: any, i: number) => (
                    <span key={i} className="vr-text-xs">{PLATFORM_ICONS[ch.type] || "🌐"}</span>
                  ))}
                </div>
                <span className="vr-text-gray-400 vr-flex-shrink-0">{item.date}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
