"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { CheckCircle2, Circle, Link2, PenSquare, Clock, Send, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface OnboardingStep {
  id: string;
  label: string;
  description: string;
  href: string;
  ctaLabel: string;
  icon: typeof Link2;
  check: () => Promise<boolean>;
}

const STEPS: OnboardingStep[] = [
  {
    id: "connect",
    label: "Connect a social account",
    description: "Link your Twitter account to start publishing",
    href: "/dashboard/settings",
    ctaLabel: "Connect account",
    icon: Link2,
    check: async () => {
      try {
        const res = await fetch("/api/v1/social-accounts");
        if (!res.ok) return false;
        const data = await res.json();
        return Array.isArray(data) && data.length > 0;
      } catch {
        return false;
      }
    },
  },
  {
    id: "create",
    label: "Create your first post",
    description: "Draft a social media post",
    href: "/dashboard/compose",
    ctaLabel: "Create post",
    icon: PenSquare,
    check: async () => {
      try {
        const res = await fetch("/api/v1/posts?limit=1");
        if (!res.ok) return false;
        const data = await res.json();
        return Array.isArray(data) && data.length > 0;
      } catch {
        return false;
      }
    },
  },
  {
    id: "schedule",
    label: "Schedule your first post",
    description: "Pick a time slot and schedule a post",
    href: "/dashboard/compose",
    ctaLabel: "Schedule post",
    icon: Clock,
    check: async () => {
      try {
        const res = await fetch("/api/v1/posts?status=SCHEDULED&limit=1");
        if (!res.ok) return false;
        const data = await res.json();
        return Array.isArray(data) && data.length > 0;
      } catch {
        return false;
      }
    },
  },
  {
    id: "publish",
    label: "Publish your first post",
    description: "Send your content live to social media",
    href: "/dashboard/compose",
    ctaLabel: "Publish post",
    icon: Send,
    check: async () => {
      try {
        const res = await fetch("/api/v1/posts?status=PUBLISHED&limit=1");
        if (!res.ok) return false;
        const data = await res.json();
        return Array.isArray(data) && data.length > 0;
      } catch {
        return false;
      }
    },
  },
];

const DISMISS_KEY = "pingcap-onboarding-dismissed";

export function OnboardingChecklist() {
  const [completed, setCompleted] = useState<Record<string, boolean>>({});
  const [loading, setLoading] = useState(true);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined" && localStorage.getItem(DISMISS_KEY) === "true") {
      // Intentional: local dismissal is an external signal we mirror into React state.
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setDismissed(true);
      setLoading(false);
      return;
    }

    Promise.all(STEPS.map(async (step) => [step.id, await step.check()] as const))
      .then((results) => {
        const map: Record<string, boolean> = {};
        for (const [id, done] of results) map[id] = done;
        setCompleted(map);
      })
      .finally(() => setLoading(false));
  }, []);

  if (dismissed || loading) return null;

  const doneCount = STEPS.filter((s) => completed[s.id]).length;

  // Hide when user has completed 3 or more steps
  if (doneCount >= 3) return null;

  const handleDismiss = () => {
    localStorage.setItem(DISMISS_KEY, "true");
    setDismissed(true);
  };

  // Find first incomplete step for highlighting
  const activeStepId = STEPS.find((s) => !completed[s.id])?.id;

  return (
    <Card className="border-blue-200 bg-blue-50/30 shadow-none">
      <CardHeader className="flex flex-row items-start justify-between pb-2">
        <div>
          <CardTitle className="text-base font-semibold text-gray-900">
            Get started with Social Hub
          </CardTitle>
          <p className="text-sm text-gray-500 mt-0.5">
            {doneCount} of {STEPS.length} steps completed
          </p>
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="h-7 text-xs text-gray-400 hover:text-gray-600"
          onClick={handleDismiss}
        >
          <X className="h-3.5 w-3.5 mr-1" />
          Hide
        </Button>
      </CardHeader>
      <CardContent className="space-y-3">
        {/* Progress bar */}
        <div className="h-1.5 w-full rounded-full bg-gray-200">
          <div
            className="h-1.5 rounded-full bg-blue-500 transition-all"
            style={{ width: `${(doneCount / STEPS.length) * 100}%` }}
          />
        </div>

        {STEPS.map((step) => {
          const done = completed[step.id];
          const isActive = step.id === activeStepId;
          const Icon = step.icon;
          return (
            <div
              key={step.id}
              className={`flex items-center gap-3 rounded-lg border p-3 ${
                done
                  ? "border-green-200 bg-green-50/50"
                  : isActive
                    ? "border-blue-300 bg-white ring-1 ring-blue-200"
                    : "border-gray-200 bg-white"
              }`}
            >
              {done ? (
                <CheckCircle2 className="h-5 w-5 shrink-0 text-green-500" />
              ) : (
                <Circle className="h-5 w-5 shrink-0 text-gray-300" />
              )}
              <div className="flex-1 min-w-0">
                <p className={`text-sm font-medium ${done ? "text-gray-400 line-through" : "text-gray-900"}`}>
                  {step.label}
                </p>
                <p className="text-xs text-gray-500">{step.description}</p>
              </div>
              {isActive && (
                <Link href={step.href}>
                  <Button size="sm" className="bg-gray-900 hover:bg-gray-800 text-white text-xs shrink-0">
                    <Icon className="h-3.5 w-3.5 mr-1" />
                    {step.ctaLabel}
                  </Button>
                </Link>
              )}
            </div>
          );
        })}
      </CardContent>
    </Card>
  );
}
