import axios from 'axios';
import { CheckCircle2, Circle, ExternalLink, X } from 'lucide-react';

import { useState } from 'react';

import { Link } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import type { SiteSummary } from '@/types';

interface SiteSetupChecklistProps {
  site: SiteSummary;
  dismissed?: boolean;
}

interface ChecklistItem {
  key: string;
  label: string;
  done: boolean;
  href: string;
  cta: string;
  optional?: boolean;
}

function getChecklistItems(site: SiteSummary): ChecklistItem[] {
  return [
    {
      key: 'gsc',
      label: 'Connect Google Search Console',
      done: site.has_gsc,
      href: route('onboarding.index', site.id),
      cta: 'Connect',
    },
    {
      key: 'analysis',
      label: 'Run first analysis',
      done: site.has_analysis,
      href: route('analyze.index', site.id),
      cta: 'Analyze',
    },
    {
      key: 'recommendations',
      label: 'Review recommendations',
      done: site.has_reviewed_recommendation,
      href: route('recommendations.index', site.id),
      cta: 'Review',
    },
    {
      key: 'wp',
      label: 'Connect WordPress',
      done: site.wp_connected,
      href: route('onboarding.index', site.id),
      cta: 'Connect',
      optional: true,
    },
    {
      key: 'ai_key',
      label: 'Enable AI Drafts',
      done: site.ai_available ?? false,
      href: route('settings.ai'),
      cta: 'Set up',
      optional: true,
    },
  ];
}

export default function SiteSetupChecklist({ site, dismissed = false }: SiteSetupChecklistProps) {
  const [isDismissed, setIsDismissed] = useState(dismissed);
  const items = getChecklistItems(site);
  const completedCount = items.filter((i) => i.done).length;

  // Don't render if all items complete
  if (completedCount === items.length) {
    return null;
  }

  // Handle dismiss
  const handleDismiss = async () => {
    setIsDismissed(true);
    try {
      await axios.post('/api/settings', {
        key: 'setup_checklist_dismissed',
        value: 'true',
      });
    } catch {
      // Silent fail
    }
  };

  // Dismissed: show compact "Resume setup" link
  if (isDismissed) {
    return (
      <div className="px-3 py-2">
        <button
          onClick={() => setIsDismissed(false)}
          className="text-xs text-primary hover:underline"
        >
          Resume setup ({completedCount}/{items.length})
        </button>
      </div>
    );
  }

  const nextIncomplete = items.find((i) => !i.done);
  const progressPercent = Math.round((completedCount / items.length) * 100);

  return (
    <div className="rounded-lg border border-amber-200 bg-amber-50/50 dark:bg-amber-950/10 dark:border-amber-800/50 p-3">
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="flex items-center gap-2 min-w-0">
          <div className="relative h-6 w-6 shrink-0">
            <svg className="h-6 w-6 -rotate-90" viewBox="0 0 24 24">
              <circle
                cx="12"
                cy="12"
                r="10"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                className="text-muted-foreground/20"
              />
              <circle
                cx="12"
                cy="12"
                r="10"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeDasharray={`${progressPercent * 0.628} 62.8`}
                strokeLinecap="round"
                className="text-primary transition-all duration-300"
              />
            </svg>
          </div>
          <p className="text-sm font-medium">
            Setup: {completedCount}/{items.length} complete
          </p>
        </div>
        {completedCount >= 1 && (
          <button
            onClick={handleDismiss}
            className="text-muted-foreground/50 hover:text-muted-foreground shrink-0"
            aria-label="Dismiss setup checklist"
          >
            <X className="h-4 w-4" />
          </button>
        )}
      </div>
      <div className="flex items-center gap-3 flex-wrap">
        {items.map((item) => (
          <div key={item.key} className="flex items-center gap-1 text-xs text-muted-foreground">
            {item.done ? (
              <CheckCircle2 className="h-3.5 w-3.5 text-green-600 dark:text-green-400 shrink-0" />
            ) : (
              <Circle className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
            )}
            <span className={item.done ? 'line-through opacity-60' : ''}>
              {item.label}
              {item.optional && !item.done ? ' (optional)' : ''}
            </span>
          </div>
        ))}
      </div>
      {nextIncomplete && (
        <div className="mt-2">
          <Button variant="outline" size="sm" asChild className="shrink-0">
            <Link href={nextIncomplete.href}>
              {nextIncomplete.cta}
              <ExternalLink className="ml-1 h-3 w-3" />
            </Link>
          </Button>
        </div>
      )}
    </div>
  );
}
