import React, { useState, useEffect } from 'react';
import { CheckCircle2, AlertCircle, ExternalLink, RefreshCw } from 'lucide-react';
import { useLearnerHub } from '../LearnerHubContext';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';
import canvasIcon from '../../assets/canvas-icon.png';

export const CanvasSetupCheckStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger } = useLearnerHub();
  const [isComplete, setIsComplete] = useState(false);
  const [refreshing, setRefreshing] = useState(true);

  const checkStatus = async () => {
    try {
      await refreshStepStatus('canvas-setup-check');
      const result = await window.learnerHubAPI.validateStep('canvas-setup-check');
      setIsComplete(result.isComplete);
    } catch (error) {
      console.error('Failed to check Canvas Setup status:', error);
    }
  };

  useEffect(() => {
    const loadInitialStatus = async () => {
      await checkStatus();
      setRefreshing(false);
    };
    loadInitialStatus();
  }, []);

  useEffect(() => {
    if (refreshTrigger > 0) {
      checkStatus();
    }
  }, [refreshTrigger]);

  const handleOpenCanvasSetup = async () => {
    await window.learnerHubAPI.openCanvasSetup();
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await checkStatus();
    } finally {
      setRefreshing(false);
    }
  };

  return (
    <div className="space-y-4">
      <Card className="px-4 py-3">
        <div className="flex items-center justify-between">
          <p className="text-sm font-medium text-foreground">
            Ensure Canvas Setup is complete before proceeding
          </p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing}
            variant="ghost"
            size="sm"
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
            {refreshing ? 'Refreshing...' : 'Refresh Status'}
          </Button>
        </div>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex items-start gap-4">
            <div className="w-10 h-10 rounded-lg overflow-hidden flex-shrink-0">
              <img src={canvasIcon} alt="Canvas Setup" className="w-full h-full object-cover" />
            </div>
            <div className="flex-1">
              <CardTitle>Canvas Setup Prerequisite</CardTitle>
              <CardDescription>
                Learner Hub development requires Canvas Setup to be completed first
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {isComplete ? (
            <Alert className="border-green-600 bg-green-50 dark:bg-green-950/20">
              <CheckCircle2 className="h-4 w-4 text-green-600" />
              <AlertDescription className="text-green-800 dark:text-green-400">
                Canvas Setup is complete. You can proceed with Learner Hub Setup.
              </AlertDescription>
            </Alert>
          ) : (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                Canvas Setup must be completed before Learner Hub Setup can begin.
                Please complete all required Canvas Setup steps first.
              </AlertDescription>
            </Alert>
          )}

          <Button
            onClick={handleOpenCanvasSetup}
            variant={isComplete ? "outline" : "default"}
            className="w-full"
          >
            <ExternalLink className="mr-2 h-4 w-4" />
            Open Canvas Setup
          </Button>

          <div className="pt-4 border-t">
            <h3 className="font-semibold mb-2">What is Canvas Setup?</h3>
            <p className="text-sm text-muted-foreground">
              Canvas Setup installs and configures all the necessary tools for
              Canvas development, including Homebrew, Docker, Git, SSH keys,
              and the inst-cli tool. These are required for Learner Hub development as well.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};
