import React, { useState, useEffect, useRef } from 'react';
import { RefreshCw, FolderOpen, GitBranch, GitCommit, ChevronDown, ChevronUp, Copy, Check } from 'lucide-react';
import { LearnerHubRepositoriesStatus, InstallResult } from '../../types';
import { useLearnerHub } from '../LearnerHubContext';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';
import { InstallResultMessage } from '../../settings/components/InstallResultMessage';
import { Badge } from '../../components/ui/badge';
import gitIcon from '../../assets/git-icon.png';

export const LearnerHubGitCloneStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger, scrollToTop } = useLearnerHub();
  const [repositoriesStatus, setRepositoriesStatus] = useState<LearnerHubRepositoriesStatus>({
    baseDirectory: null,
    learnerHub: {
      exists: false,
      isValidRepo: false,
      remoteUrl: null,
      currentBranch: null,
      lastCommit: null
    },
    configExists: false,
    configured: false
  });
  const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
  const [cloning, setCloning] = useState(false);
  const [resetting, setResetting] = useState(false);
  const [refreshing, setRefreshing] = useState(true);
  const [result, setResult] = useState<InstallResult | null>(null);
  const [showAboutStep, setShowAboutStep] = useState(false);
  const [cloneOutput, setCloneOutput] = useState<string>('');
  const [showCloneOutput, setShowCloneOutput] = useState(false);
  const [resetOutput, setResetOutput] = useState<string>('');
  const [showResetOutput, setShowResetOutput] = useState(false);
  const [copiedOutput, setCopiedOutput] = useState<string | null>(null);
  const outputEndRef = useRef<HTMLDivElement>(null);

  const checkStatus = async () => {
    try {
      const config = await window.learnerHubAPI.getConfig();

      if (config.exists && config.baseDirectory) {
        setSelectedFolder(config.baseDirectory);
      }

      const status = await window.learnerHubAPI.getRepositoryStatus(
        selectedFolder || config.baseDirectory
      );
      setRepositoriesStatus(status);

      await refreshStepStatus('learner-hub-git-clone');
    } catch (error) {
      console.error('Failed to check learner-hub repository status:', error);
    }
  };

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

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

  useEffect(() => {
    if (cloneOutput || resetOutput) {
      setTimeout(() => {
        outputEndRef.current?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    }
  }, [cloneOutput, resetOutput]);

  const handleSelectFolder = async () => {
    try {
      const folder = await window.learnerHubAPI.selectCloneFolder();
      if (folder) {
        setSelectedFolder(folder);
        await window.learnerHubAPI.saveCloneFolder(folder);
        const status = await window.learnerHubAPI.getRepositoryStatus(folder);
        setRepositoriesStatus(status);
        await refreshStepStatus('learner-hub-git-clone');
        setResult(null);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to select folder'
      });
    }
  };

  const handleClone = async () => {
    if (!selectedFolder) {
      setResult({
        success: false,
        message: 'Please select a folder first'
      });
      return;
    }

    setCloning(true);
    setResult(null);
    setCloneOutput('');
    setShowCloneOutput(true);

    const cleanup = window.learnerHubAPI.onCloneOutput((output) => {
      setCloneOutput((prev) => prev + output);
    });

    try {
      const cloneResult = await window.learnerHubAPI.cloneRepository(selectedFolder);
      setResult(cloneResult);

      if (cloneResult.success) {
        setTimeout(() => {
          scrollToTop();
          checkStatus();
        }, 500);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to clone repository'
      });
    } finally {
      setCloning(false);
      cleanup();
    }
  };

  const handleReset = async () => {
    if (!selectedFolder) {
      return;
    }

    const confirmed = window.confirm(
      'This will:\n' +
      '1. Remove all untracked files (git clean -fdx)\n' +
      '2. Checkout main/master branch\n' +
      '3. Pull latest changes from origin\n\n' +
      'All local changes will be lost. Continue?'
    );

    if (!confirmed) {
      return;
    }

    setResetting(true);
    setResult(null);
    setResetOutput('');
    setShowResetOutput(true);

    const cleanup = window.learnerHubAPI.onResetOutput((output) => {
      setResetOutput((prev) => prev + output);
    });

    try {
      const resetResult = await window.learnerHubAPI.resetRepository(selectedFolder);
      setResult(resetResult);

      if (resetResult.success) {
        setTimeout(() => {
          scrollToTop();
          checkStatus();
        }, 500);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to reset repository'
      });
    } finally {
      setResetting(false);
      cleanup();
    }
  };

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

  const isConfigured = repositoriesStatus.configured;

  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">
            Clone the learner-hub repository
          </p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || cloning || resetting}
            variant="ghost"
            size="sm"
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
            {refreshing ? 'Refreshing...' : 'Refresh Status'}
          </Button>
        </div>
      </Card>

      {/* About This Step Section */}
      <Card className="p-5">
        <div className="space-y-3">
          <button
            onClick={() => setShowAboutStep(!showAboutStep)}
            className="flex items-center gap-2 text-sm w-full text-foreground hover:opacity-80"
          >
            {showAboutStep ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
            About This Step
          </button>

          {showAboutStep && (
            <div className="p-4 rounded-lg text-sm space-y-4 bg-muted text-muted-foreground">
              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  What does this step do?
                </p>
                <p>
                  This step clones the learner-hub repository from GitHub to your local machine.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  You need a local copy of the learner-hub repository to develop Learner Hub features for Canvas.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  What actions does this step perform?
                </p>
                <ul className="list-disc list-inside space-y-1">
                  <li>Allows you to select a folder where the repository will be cloned</li>
                  <li>Checks if the repository is already cloned at the selected location</li>
                  <li>Clones learner-hub from GitHub</li>
                  <li>Creates a configuration file at ~/.inst-agent/learner-hub.yml</li>
                  <li>Displays last commit information for the repository</li>
                  <li>Provides option to reset the repository if needed</li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>

      {result && (
        <InstallResultMessage
          result={result}
          onDismiss={() => setResult(null)}
        />
      )}

      {/* Repository Status Card */}
      <Card className="p-5">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-3">
            <div className="w-12 h-12 rounded overflow-hidden flex-shrink-0">
              <img
                src={gitIcon}
                alt="Git"
                className="w-full h-full object-cover"
              />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">
                Learner Hub Repository
              </h3>
              {isConfigured && repositoriesStatus.learnerHub.currentBranch && (
                <div className="flex items-center gap-2 mt-1">
                  <Badge variant="outline" className="text-xs">
                    <GitBranch className="h-3 w-3 mr-1" />
                    learner-hub: {repositoriesStatus.learnerHub.currentBranch}
                  </Badge>
                </div>
              )}
            </div>
          </div>
          <div
            className={`px-3 py-1 rounded-full text-sm font-medium ${
              isConfigured
                ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400'
                : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400'
            }`}
          >
            {isConfigured ? 'Configured' : 'Not Configured'}
          </div>
        </div>

        <div className="space-y-4">
          {/* Folder Selection */}
          <div>
            <label className="text-sm font-medium mb-2 block text-foreground">
              Clone Location
            </label>
            <p className="text-xs text-muted-foreground mb-3">
              Select a folder where the repository will be cloned. It will be created in a subdirectory: <code className="bg-muted px-1 rounded">learner-hub</code>.
            </p>
            <div className="flex gap-2">
              <input
                type="text"
                readOnly
                value={selectedFolder || 'No folder selected'}
                className="flex-1 px-3 py-2 text-sm rounded border bg-muted text-muted-foreground"
              />
              <Button
                onClick={handleSelectFolder}
                disabled={cloning || resetting}
                variant="outline"
                size="sm"
              >
                <FolderOpen className="h-4 w-4 mr-2" />
                Select Folder
              </Button>
            </div>
            {selectedFolder && (
              <p className="text-xs mt-2 text-muted-foreground">
                Repository will be at: {selectedFolder}/learner-hub
              </p>
            )}
          </div>

          {/* Last Commit Info */}
          {repositoriesStatus.learnerHub.lastCommit && (
            <div className="p-3 rounded-lg bg-muted">
              <div className="flex items-start gap-2">
                <GitCommit className="h-4 w-4 mt-0.5 text-muted-foreground" />
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-medium mb-1 text-foreground">
                    learner-hub - Last Commit
                  </p>
                  <p className="text-xs text-muted-foreground">
                    <span className="font-mono">{repositoriesStatus.learnerHub.lastCommit.hash}</span> - {repositoriesStatus.learnerHub.lastCommit.message}
                  </p>
                  <p className="text-xs mt-1 text-muted-foreground">
                    {repositoriesStatus.learnerHub.lastCommit.author} • {new Date(repositoriesStatus.learnerHub.lastCommit.date).toLocaleString()}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Action Buttons */}
          <div className="space-y-2">
            {!isConfigured ? (
              <Button
                onClick={handleClone}
                disabled={!selectedFolder || cloning}
                className="w-full"
              >
                {cloning ? 'Cloning Repository...' : 'Clone Repository'}
              </Button>
            ) : (
              <Button
                onClick={handleReset}
                disabled={resetting}
                className="w-full"
                variant="outline"
              >
                {resetting ? 'Resetting...' : 'Reset Repository'}
              </Button>
            )}
          </div>

          {!selectedFolder && (
            <Alert variant="warning">
              <AlertDescription>
                <p className="text-xs">
                  Please select a folder where the learner-hub repository will be cloned.
                </p>
              </AlertDescription>
            </Alert>
          )}
        </div>
      </Card>

      {showCloneOutput && (
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-foreground">
              Clone Output
            </h4>
            <div className="flex items-center gap-1">
              <button
                onClick={() => { navigator.clipboard.writeText(cloneOutput); setCopiedOutput('clone'); setTimeout(() => setCopiedOutput(null), 2000); }}
                className="p-1 hover:bg-secondary rounded"
                title="Copy output"
              >
                {copiedOutput === 'clone' ? <Check className="h-3.5 w-3.5 text-green-600" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}
              </button>
              <Button
                onClick={() => setShowCloneOutput(false)}
                variant="ghost"
                size="sm"
                disabled={cloning}
              >
                Hide
              </Button>
            </div>
          </div>
          <div
            className="bg-[#1a1a1a] text-[#00ff00] font-mono text-xs p-4 rounded-md overflow-auto max-h-96"
            style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
          >
            {cloneOutput || 'Waiting for output...'}
            <div ref={outputEndRef} />
          </div>
        </Card>
      )}

      {showResetOutput && (
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-foreground">
              Reset Output
            </h4>
            <div className="flex items-center gap-1">
              <button
                onClick={() => { navigator.clipboard.writeText(resetOutput); setCopiedOutput('reset'); setTimeout(() => setCopiedOutput(null), 2000); }}
                className="p-1 hover:bg-secondary rounded"
                title="Copy output"
              >
                {copiedOutput === 'reset' ? <Check className="h-3.5 w-3.5 text-green-600" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}
              </button>
              <Button
                onClick={() => setShowResetOutput(false)}
                variant="ghost"
                size="sm"
                disabled={resetting}
              >
                Hide
              </Button>
            </div>
          </div>
          <div
            className="bg-[#1a1a1a] text-[#00ff00] font-mono text-xs p-4 rounded-md overflow-auto max-h-96"
            style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
          >
            {resetOutput || 'Waiting for output...'}
            <div ref={outputEndRef} />
          </div>
        </Card>
      )}
    </div>
  );
};
