import React, { useState } from 'react';
import { ChevronLeft, ChevronRight, Check, Loader2 } from 'lucide-react';
import { useLearnerHub } from '../LearnerHubContext';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';

export const WizardFooter: React.FC = () => {
  const {
    steps,
    currentStepIndex,
    stepValidation,
    nextStep,
    previousStep,
    validateCurrentStep,
    completeWizard
  } = useLearnerHub();

  const [validating, setValidating] = useState(false);
  const [completing, setCompleting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const currentStep = steps[currentStepIndex];
  const validation = currentStep ? stepValidation.get(currentStep.id) : null;
  const isFirstStep = currentStepIndex === 0;
  const isLastStep = currentStepIndex === steps.length - 1;

  const handleNext = async () => {
    setMessage(null);
    setValidating(true);
    try {
      const result = await validateCurrentStep();
      if (!result.canProceed) {
        setMessage({ type: 'error', text: result.message || 'Cannot proceed to next step' });
        setValidating(false);
        return;
      }
      if (!result.isComplete && currentStep?.required) {
        setMessage({ type: 'error', text: 'This step must be completed before proceeding' });
        setValidating(false);
        return;
      }
      nextStep();
      setMessage(null);
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to validate step' });
    } finally {
      setValidating(false);
    }
  };

  const handleComplete = async () => {
    setMessage(null);
    setCompleting(true);
    try {
      const result = await validateCurrentStep();
      if (!result.isComplete && currentStep?.required) {
        setMessage({ type: 'error', text: 'Please complete this step before finishing' });
        setCompleting(false);
        return;
      }
      await completeWizard();
      setMessage({ type: 'success', text: 'Learner Hub Setup complete! You can now close this window.' });
      setTimeout(() => { window.close(); }, 2000);
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to complete setup' });
    } finally {
      setCompleting(false);
    }
  };

  const handleSkip = () => {
    setMessage(null);
    nextStep();
  };

  const handleWheel = (e: React.WheelEvent) => {
    e.stopPropagation();
  };

  return (
    <div className="border-t border-border bg-secondary px-6 py-4" onWheel={handleWheel}>
      {message && (
        <Alert variant={message.type === 'success' ? 'success' : 'destructive'} className="mb-3">
          <AlertDescription className="text-sm">{message.text}</AlertDescription>
        </Alert>
      )}

      <div className="flex items-center justify-between">
        {!isFirstStep ? (
          <Button onClick={previousStep} variant="outline" size="default">
            <ChevronLeft className="h-4 w-4 mr-2" />
            Previous
          </Button>
        ) : (
          <div />
        )}

        <div className="flex items-center gap-3">
          {!isLastStep && !currentStep?.required && (
            <Button onClick={handleSkip} variant="ghost" size="default" className="text-foreground hover:bg-accent">
              Skip
            </Button>
          )}

          {isLastStep ? (
            <Button onClick={handleComplete} disabled={completing || validating} className="bg-green-600 hover:bg-green-700">
              {completing ? (
                <><Loader2 className="h-4 w-4 mr-2 animate-spin" />Completing...</>
              ) : (
                <><Check className="h-4 w-4 mr-2" />Complete Learner Hub Setup</>
              )}
            </Button>
          ) : (
            <Button
              onClick={handleNext}
              disabled={validating || (!validation?.canProceed && validation !== undefined)}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {validating ? (
                <><Loader2 className="h-4 w-4 mr-2 animate-spin" />Validating...</>
              ) : (
                <>Next<ChevronRight className="h-4 w-4 ml-2" /></>
              )}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
};
