'use client';

import { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from '../ui/card';
import { Checkbox } from '../ui/checkbox';
import { Label } from '../ui/label';
import { Sparkles, PlayCircle, HelpCircle, X } from 'lucide-react';

const STORAGE_KEY = 'workflow_guidance_dismissed';

export interface WorkflowEmptyStateProps {
  onOpenTemplateGallery: () => void;
  onStartFromScratch: () => void;
  onOpenHelp?: () => void;
}

/**
 * Empty State Component for Workflow Canvas
 *
 * Provides first-time user guidance with two paths:
 * 1. Template Gallery - Pre-built workflows to learn from
 * 2. Start From Scratch - Opens node palette with guidance
 *
 * Features:
 * - localStorage-based dismissal (respects user preference)
 * - Non-intrusive inline design (not a modal)
 * - Action-oriented messaging (not "Welcome!")
 * - Re-accessible via help button
 */
export function WorkflowEmptyState({
  onOpenTemplateGallery,
  onStartFromScratch,
  onOpenHelp,
}: WorkflowEmptyStateProps) {
  const [isDismissed, setIsDismissed] = useState(true);
  const [dontShowAgain, setDontShowAgain] = useState(false);

  useEffect(() => {
    // Check if user has dismissed guidance
    const dismissed = localStorage.getItem(STORAGE_KEY) === 'true';
    setIsDismissed(dismissed);
  }, []);

  const handleTemplateGalleryClick = () => {
    if (dontShowAgain) {
      localStorage.setItem(STORAGE_KEY, 'true');
    }
    setIsDismissed(true);
    onOpenTemplateGallery();
  };

  const handleStartFromScratchClick = () => {
    if (dontShowAgain) {
      localStorage.setItem(STORAGE_KEY, 'true');
    }
    setIsDismissed(true);
    onStartFromScratch();
  };

  const handleDismiss = () => {
    if (dontShowAgain) {
      localStorage.setItem(STORAGE_KEY, 'true');
    }
    setIsDismissed(true);
  };

  if (isDismissed) {
    // Show persistent help button for returning users
    return (
      <div className="absolute bottom-6 right-6 z-10">
        <Button
          variant="outline"
          size="icon"
          onClick={onOpenHelp}
          className="h-12 w-12 rounded-full shadow-lg hover:shadow-xl transition-all"
          title="Need help? View templates and guidance"
        >
          <HelpCircle className="h-5 w-5" />
        </Button>
      </div>
    );
  }

  return (
    <div
      className="flex items-center justify-center z-10"
      role="dialog"
      aria-labelledby="welcome-title"
      aria-describedby="welcome-description"
      aria-modal="false"
    >
      <Card className="w-full max-w-[720px] pointer-events-auto animate-in fade-in-0 zoom-in-95 duration-300 relative">
        {/* Close button */}
        <button
          onClick={handleDismiss}
          aria-label="Close welcome panel"
          aria-keyshortcuts="Escape"
          className="absolute right-4 top-4 rounded-full p-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
        >
          <X className="w-5 h-5" aria-hidden="true" />
        </button>

        <CardHeader className="text-center pb-4 pt-10 px-10">
          <CardTitle id="welcome-title" className="text-2xl font-semibold">
            Welcome to Workflow Builder
          </CardTitle>
          <CardDescription
            id="welcome-description"
            className="text-sm text-muted-foreground leading-relaxed mt-2"
          >
            Create automated workflows with browser actions, logic, and AI
          </CardDescription>
        </CardHeader>

        <CardContent className="flex flex-col gap-6 px-10 pb-10">
          {/* Option 1: Template Gallery */}
          <button
            onClick={handleTemplateGalleryClick}
            className="block w-full group text-left"
            aria-label="Browse template gallery"
            aria-describedby="template-gallery-desc"
          >
            <Card className="cursor-pointer transition-all duration-150 hover:shadow-md hover:border-primary/50 hover:scale-[1.02]">
              <CardContent className="pt-6 pb-6">
                <div className="flex items-start gap-4">
                  <div className="flex-shrink-0">
                    <div className="h-12 w-12 rounded-lg bg-primary/5 flex items-center justify-center group-hover:bg-primary/10 transition-colors">
                      <Sparkles className="h-6 w-6 text-primary/60" />
                    </div>
                  </div>
                  <div className="flex-1 text-left">
                    <h3 className="font-medium text-base mb-1">
                      Browse Template Gallery
                    </h3>
                    <p className="text-xs text-muted-foreground leading-relaxed">
                      Start with a pre-built workflow and customize it to your
                      needs. Perfect for learning common patterns.
                    </p>
                    <div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
                      <span className="inline-flex items-center gap-1">
                        ⭐⭐⭐⭐⭐ Popular choice
                      </span>
                      <span>•</span>
                      <span>5 templates available</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
            <span id="template-gallery-desc" className="sr-only">
              Choose from 5 pre-built workflow templates including login flows,
              data extraction, API integration, multi-page navigation, and form
              submission.
            </span>
          </button>

          {/* Option 2: Start From Scratch */}
          <button
            onClick={handleStartFromScratchClick}
            className="block w-full group text-left"
            aria-label="Start from scratch"
            aria-describedby="start-scratch-desc"
          >
            <Card className="cursor-pointer transition-all duration-150 hover:shadow-md hover:border-primary/50 hover:scale-[1.02]">
              <CardContent className="pt-6 pb-6">
                <div className="flex items-start gap-4">
                  <div className="flex-shrink-0">
                    <div className="h-12 w-12 rounded-lg bg-primary/5 flex items-center justify-center group-hover:bg-primary/10 transition-colors">
                      <PlayCircle className="h-6 w-6 text-primary/60" />
                    </div>
                  </div>
                  <div className="flex-1 text-left">
                    <h3 className="font-medium text-base mb-1">
                      Start From Scratch
                    </h3>
                    <p className="text-xs text-muted-foreground leading-relaxed">
                      Build your workflow from the ground up. We&apos;ll
                      highlight the node palette and show you how to get started.
                    </p>
                    <div className="mt-2 text-xs text-muted-foreground">
                      For experienced users
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
            <span id="start-scratch-desc" className="sr-only">
              Create a custom workflow by adding nodes from the node palette.
              Ideal for users familiar with workflow automation.
            </span>
          </button>

          {/* Don't show again checkbox */}
          <div className="flex items-center justify-between pt-4 border-t">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="dontShowAgain"
                checked={dontShowAgain}
                onCheckedChange={(checked) => setDontShowAgain(checked === true)}
              />
              <Label
                htmlFor="dontShowAgain"
                className="text-sm text-muted-foreground cursor-pointer"
              >
                Don&apos;t show this again
              </Label>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleDismiss}
              className="text-muted-foreground hover:text-foreground"
            >
              Close
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

/**
 * Hook to manage empty state visibility and reset.
 */
export function useWorkflowEmptyState() {
  const [isGuidanceDismissed, setIsGuidanceDismissed] = useState(true);

  useEffect(() => {
    const dismissed = localStorage.getItem(STORAGE_KEY) === 'true';
    setIsGuidanceDismissed(dismissed);
  }, []);

  const resetGuidance = () => {
    localStorage.removeItem(STORAGE_KEY);
    setIsGuidanceDismissed(false);
  };

  const dismissGuidance = () => {
    localStorage.setItem(STORAGE_KEY, 'true');
    setIsGuidanceDismissed(true);
  };

  return {
    isGuidanceDismissed,
    resetGuidance,
    dismissGuidance,
  };
}
