'use client';

import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { MathBlock } from '@/components/math/MathFormula';
import { ChevronDown, ChevronUp, BookOpen, Check, Play } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * Solution step interface
 */
export interface SolutionStep {
  id: string;
  title: string;
  content: string;
  isMath?: boolean;
  explanation?: string;
}

/**
 * Solution data interface
 */
export interface Solution {
  id: string;
  title: string;
  steps: SolutionStep[];
  finalAnswer: string;
  summary?: string;
}

/**
 * StepByStepSolution component props
 */
export interface StepByStepSolutionProps {
  /**
   * Solution data
   */
  solution: Solution;

  /**
   * Additional CSS classes
   */
  className?: string;

  /**
   * Compact mode
   */
  compact?: boolean;

  /**
   * Auto-reveal all steps
   */
  autoReveal?: boolean;
}

/**
 * StepByStepSolution component - displays step-by-step solution
 */
export function StepByStepSolution({
  solution,
  className,
  compact = false,
  autoReveal = false,
}: StepByStepSolutionProps) {
  const [revealedSteps, setRevealedSteps] = useState<Set<number>>(
    autoReveal ? new Set(solution.steps.map((_, i) => i)) : new Set([0])
  );
  const [allRevealed, setAllRevealed] = useState(autoReveal);

  const toggleStep = (index: number) => {
    setRevealedSteps((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(index)) {
        newSet.delete(index);
      } else {
        newSet.add(index);
      }
      return newSet;
    });
  };

  const revealAll = () => {
    setAllRevealed(true);
    setRevealedSteps(new Set(solution.steps.map((_, i) => i)));
  };

  const revealNext = () => {
    const nextIndex = Math.max(...revealedSteps) + 1;
    if (nextIndex < solution.steps.length) {
      setRevealedSteps((prev) => new Set(prev).add(nextIndex));
    }
  };

  const canRevealNext = Math.max(...revealedSteps) < solution.steps.length - 1;

  return (
    <Card className={cn('border-blue-200 dark:border-blue-800', className)}>
      <CardHeader>
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-center gap-2">
            <BookOpen className="h-5 w-5 text-blue-600 dark:text-blue-400" />
            <div>
              <CardTitle className="text-lg">Step-by-Step Solution</CardTitle>
              {!compact && solution.summary && (
                <CardDescription className="mt-1">{solution.summary}</CardDescription>
              )}
            </div>
          </div>

          {!allRevealed && (
            <div className="flex gap-2">
              {canRevealNext && (
                <Button size="sm" variant="outline" onClick={revealNext} className="gap-2">
                  <Play className="h-3.5 w-3.5" />
                  Next Step
                </Button>
              )}
              <Button size="sm" variant="secondary" onClick={revealAll}>
                Show All
              </Button>
            </div>
          )}
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* Steps */}
        <div className="space-y-3">
          {solution.steps.map((step, index) => {
            const isRevealed = revealedSteps.has(index);
            const isPreviousRevealed = index === 0 || revealedSteps.has(index - 1);

            return (
              <div
                key={step.id}
                className={cn(
                  'rounded-lg border overflow-hidden transition-all',
                  isRevealed
                    ? 'bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800'
                    : 'bg-muted border-muted-foreground/20',
                  !isPreviousRevealed && !isRevealed && 'opacity-50',
                  isRevealed && 'animate-in fade-in slide-in-from-bottom-2 duration-300'
                )}
                style={{ animationDelay: `${index * 50}ms` }}
              >
                <button
                  onClick={() => isPreviousRevealed && toggleStep(index)}
                  disabled={!isPreviousRevealed}
                  className={cn(
                    'w-full flex items-center justify-between p-4 text-left transition-colors',
                    isPreviousRevealed && !isRevealed && 'hover:bg-muted/80 cursor-pointer',
                    !isPreviousRevealed && 'cursor-not-allowed'
                  )}
                  aria-expanded={isRevealed}
                >
                  <div className="flex items-center gap-3 flex-1">
                    <div
                      className={cn(
                        'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold',
                        isRevealed
                          ? 'bg-blue-200 dark:bg-blue-800 text-blue-800 dark:text-blue-200'
                          : 'bg-muted-foreground/20 text-muted-foreground'
                      )}
                    >
                      {isRevealed ? <Check className="h-4 w-4" /> : index + 1}
                    </div>

                    <div>
                      <h4 className={cn('font-medium', isRevealed ? 'text-blue-900 dark:text-blue-100' : 'text-muted-foreground')}>
                        {step.title}
                      </h4>
                      {compact && isRevealed && step.explanation && (
                        <p className="text-sm text-muted-foreground mt-1">{step.explanation}</p>
                      )}
                    </div>
                  </div>

                  {isPreviousRevealed && (
                    <div className="flex-shrink-0 ml-2">
                      {isRevealed ? (
                        <ChevronUp className="h-5 w-5 text-muted-foreground" />
                      ) : (
                        <ChevronDown className="h-5 w-5 text-muted-foreground" />
                      )}
                    </div>
                  )}
                </button>

                {isRevealed && (
                  <div className="overflow-hidden animate-in fade-in slide-in-from-top-2 duration-300">
                    <div className="px-4 pb-4 pt-0">
                        <div className="ml-11 pl-4 border-l-2 border-blue-300 dark:border-blue-700">
                          {step.isMath ? (
                            <MathBlock formula={step.content} />
                          ) : (
                            <p className="text-sm text-blue-900 dark:text-blue-100 whitespace-pre-wrap">
                              {step.content}
                            </p>
                          )}

                          {step.explanation && !compact && (
                            <p className="text-sm text-muted-foreground mt-3 italic">
                              {step.explanation}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
              </div>
            );
          })}
        </div>

        {/* Final Answer */}
        <div
          className={cn(
            'rounded-lg border-2 p-6 text-center transition-all duration-300',
            allRevealed
              ? 'bg-green-50 dark:bg-green-950 border-green-300 dark:border-green-700'
              : 'bg-muted border-muted-foreground/20',
            allRevealed && 'animate-in fade-in zoom-in duration-500'
          )}
        >
          <p className="text-sm font-medium text-muted-foreground mb-2">Final Answer:</p>
          {allRevealed ? (
            <MathBlock formula={solution.finalAnswer} />
          ) : (
            <p className="text-sm text-muted-foreground italic">
              Complete all steps to reveal the final answer
            </p>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

/**
 * Compact solution summary component
 */
export interface SolutionSummaryProps {
  solution: Solution;
  onClick?: () => void;
  className?: string;
}

export function SolutionSummary({ solution, onClick, className }: SolutionSummaryProps) {
  return (
    <Button
      variant="outline"
      onClick={onClick}
      className={cn('w-full justify-start gap-2', className)}
    >
      <BookOpen className="h-4 w-4" />
      <span>View Solution</span>
      <span className="text-xs text-muted-foreground">
        ({solution.steps.length} steps)
      </span>
    </Button>
  );
}
