import React, { useState, useEffect } from 'react';
import { CheckCircle2, AlertCircle, Copy, Check, ExternalLink, RefreshCw , ChevronDown, ChevronUp, Terminal } from 'lucide-react';
import { SshKeyStatus } from '../../types';
import { useSetupWizard } from '../SetupWizardContext';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Label } from '../../components/ui/label';
import { Alert, AlertDescription } from '../../components/ui/alert';
import { Badge } from '../../components/ui/badge';
import githubIcon from '../../assets/github-icon.png';

export const GitHubSetupStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger } = useSetupWizard();
  const [sshKeyStatus, setSshKeyStatus] = useState<SshKeyStatus | null>(null);
  const [showAboutStep, setShowAboutStep] = useState(false);
  const [showTroubleshooting, setShowTroubleshooting] = useState(false);
  const [copied, setCopied] = useState(false);
  const [completed, setCompleted] = useState(false);
  const [refreshing, setRefreshing] = useState(true);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [result, setResult] = useState<any>(null);

  const checkStatus = async (forceRefresh = false) => {
    try {
      // Get SSH key status to display the public key
      const status = await window.setupWizardAPI.getSshKeyStatus(undefined, forceRefresh);
      setSshKeyStatus(status);

      // Refresh validation status to get latest completion state
      await refreshStepStatus('github-setup');

      // Check if this step is now completed
      const onboardingState = await window.setupWizardAPI.getState();
      const stepData = onboardingState.stepStatus['github-setup'];
      setCompleted(stepData?.completed || false);
    } catch (error) {
      console.error('Failed to check GitHub setup status:', error);
    } finally {
    }
  };

  useEffect(() => {
    const loadInitialStatus = async () => {
      await checkStatus(true); // Force refresh on initial load to bypass cache
      setRefreshing(false);
    };
    loadInitialStatus();
  }, []);

  // Listen to refresh trigger from context
  useEffect(() => {
    if (refreshTrigger > 0) {
      handleRefresh();
    }
  }, [refreshTrigger]);

  const handleCopyPublicKey = () => {
    if (sshKeyStatus?.publicKeyContent) {
      navigator.clipboard.writeText(sshKeyStatus.publicKeyContent);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };


  const handleRefresh = async () => {
    setRefreshing(true);
    await checkStatus(true); // Force refresh
    setRefreshing(false);
  };

  const handleOpenTerminal = async () => {
    try {
      const result = await window.setupWizardAPI.openTerminal();
      if (!result.success) {
        setResult({
          success: false,
          message: result.message || 'Failed to open Terminal'
        });
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to open Terminal'
      });
    }
  };

  const handleCopyCode = async (code: string, id: string) => {
    try {
      await navigator.clipboard.writeText(code);
      setCopiedCode(id);
      setTimeout(() => setCopiedCode(null), 2000);
    } catch (error) {
      console.error('Failed to copy code:', error);
    }
  };

  const hasPublicKey = sshKeyStatus?.keysExist && sshKeyStatus?.publicKeyContent;

  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">
            Add SSH key to GitHub for repository access
          </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>

      {/* 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 is GitHub?
                </p>
                <p>
                  GitHub is the world's largest Git hosting platform where Instructure hosts some Canvas repositories and collaborates on open-source projects. Many Canvas-related tools, plugins, and community contributions are hosted on GitHub.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Adding your SSH public key to GitHub enables secure, passwordless authentication when cloning Canvas-related repositories, contributing to open-source projects, and accessing private repositories you may need for development work.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  How does validation work?
                </p>
                <ul className="list-disc list-inside space-y-1">
                  <li>Displays your SSH public key for easy copying</li>
                  <li>Provides direct link to GitHub SSH Keys settings</li>
                  <li>Automatically tests SSH connection using your configured private key</li>
                  <li>Uses command: <code className="bg-secondary px-1 rounded text-xs">ssh -T -i &lt;private_key&gt; git@github.com</code></li>
                  <li>Verifies authentication and marks step complete when connection succeeds</li>
                  <li>No manual completion needed - validation is automatic</li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>

      <Card className="p-5">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg overflow-hidden flex-shrink-0">
              <img src={githubIcon} alt="GitHub" className="w-full h-full object-cover" />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">
                GitHub
              </h3>
              <div className="mt-1">
                {completed ? (
                  <Badge variant="success" className="text-xs">
                    <CheckCircle2 className="h-3.5 w-3.5 mr-1" />
                    Configured
                  </Badge>
                ) : (
                  <Badge variant="secondary" className="text-xs">
                    <AlertCircle className="h-3.5 w-3.5 mr-1" />
                    Not Configured
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="space-y-4">
          {!hasPublicKey ? (
            <Alert variant="warning">
              <AlertCircle className="h-5 w-5" />
              <AlertDescription>
                <p className="font-medium mb-1">SSH Key Required</p>
                <p className="text-xs">
                  Please complete the SSH Keys step first to generate or select your SSH key pair.
                </p>
              </AlertDescription>
            </Alert>
          ) : (
            <>
              <p className="text-[13px] text-muted-foreground">
                Add your SSH public key to GitHub to access repositories.
              </p>

              <div className="space-y-2">
                <Label>Your SSH Public Key</Label>
                <div className="relative">
                  <textarea
                    readOnly
                    value={sshKeyStatus?.publicKeyContent || ''}
                    className="w-full h-24 p-3 text-xs font-mono rounded border resize-none bg-muted text-muted-foreground"
                  />
                  <Button
                    onClick={handleCopyPublicKey}
                    size="sm"
                    className="absolute bottom-3 right-2"
                  >
                    {copied ? (
                      <>
                        <Check className="h-3.5 w-3.5 mr-1" />
                        Copied!
                      </>
                    ) : (
                      <>
                        <Copy className="h-3.5 w-3.5 mr-1" />
                        Copy
                      </>
                    )}
                  </Button>
                </div>
              </div>

              <div
                className="p-4 rounded-lg text-sm space-y-3 bg-muted text-muted-foreground"
              >
                <p className="font-medium text-foreground">
                  Adding SSH key to GitHub
                </p>
                <ol className="list-decimal list-inside space-y-2">
                  <li>
                    Go to{' '}
                    <a
                      href="https://github.com/settings/keys"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 inline-flex items-center gap-1"
                    >
                      GitHub SSH Keys Settings
                      <ExternalLink className="h-3 w-3" />
                    </a>
                  </li>
                  <li>Click "New SSH key" button</li>
                  <li>
                    Add a title (e.g., "Work Laptop") and paste your public key in the "Key" field
                  </li>
                  <li>Click "Add SSH key" to save</li>
                </ol>

                <p className="text-xs mt-3 text-muted-foreground">
                  <strong>Note:</strong> After adding your SSH key, you can test the connection by running{' '}
                  <code className="bg-secondary px-1 rounded">ssh -T git@github.com</code> in your terminal.
                </p>
              </div>

              {completed ? (
                <Alert variant="success">
                  <CheckCircle2 className="h-5 w-5" />
                  <AlertDescription>
                    <p className="font-medium mb-1">GitHub SSH connection verified</p>
                    <p className="text-xs">
                      Your SSH key is properly configured with GitHub. You can now access repositories.
                    </p>
                  </AlertDescription>
                </Alert>
              ) : (
                <Alert variant="default">
                  <AlertCircle className="h-5 w-5" />
                  <AlertDescription>
                    <p className="font-medium mb-1">Automatic validation</p>
                    <p className="text-xs">
                      After adding your SSH key to GitHub, click "Refresh Status" to verify the connection automatically.
                    </p>
                  </AlertDescription>
                </Alert>
              )}
            </>
          )}
        </div>
      </Card>

      <Card className="p-5">
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <button
              onClick={() => setShowTroubleshooting(!showTroubleshooting)}
              className="flex items-center gap-2 text-sm text-foreground hover:opacity-80"
            >
              {showTroubleshooting ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
              Troubleshooting
            </button>
            {showTroubleshooting && (
              <Button
                onClick={handleOpenTerminal}
                variant="outline"
                size="sm"
                className="h-8 text-xs"
              >
                <Terminal className="h-3.5 w-3.5 mr-1.5" />
                Open Terminal
              </Button>
            )}
          </div>

          {showTroubleshooting && (
            <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">
                  Testing SSH connection to GitHub
                </p>
                <p>
                  To verify your SSH key is properly configured:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    {sshKeyStatus?.privateKeyPath
                      ? `ssh -T -i "${sshKeyStatus.privateKeyPath}" -o IdentitiesOnly=yes git@github.com`
                      : 'ssh -T git@github.com'}
                  </code>
                  <button
                    onClick={() => handleCopyCode(
                      sshKeyStatus?.privateKeyPath
                        ? `ssh -T -i "${sshKeyStatus.privateKeyPath}" -o IdentitiesOnly=yes git@github.com`
                        : 'ssh -T git@github.com',
                      'ssh-github'
                    )}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'ssh-github' ? (
                      <Check className="h-3.5 w-3.5 text-green-600" />
                    ) : (
                      <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                    )}
                  </button>
                </div>
                <p className="text-xs mt-2">
                  You should see "Hi username! You've successfully authenticated..." if it works. The <code className="bg-secondary px-1 rounded">-i</code> flag explicitly specifies which private key to use, and <code className="bg-secondary px-1 rounded">IdentitiesOnly=yes</code> ensures only this key is tried.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  SSH key format issues
                </p>
                <p>
                  GitHub requires properly formatted SSH keys:
                </p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Key must be in OpenSSH format (starts with "ssh-rsa" or "ssh-ed25519")</li>
                  <li>Remove any line breaks or extra whitespace</li>
                  <li>Copy the entire key including the comment at the end</li>
                </ul>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Manually adding key to GitHub
                </p>
                <ol className="list-decimal list-inside space-y-1">
                  <li>Visit{' '}
                    <a
                      href="https://github.com/settings/keys"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 underline hover:text-blue-700 dark:hover:text-blue-300"
                    >
                      GitHub SSH Keys
                    </a>
                  </li>
                  <li>Click "New SSH key"</li>
                  <li>Give it a title (e.g., "Mac - Canvas Development")</li>
                  <li>Paste your public key</li>
                  <li>Click "Add SSH key"</li>
                  <li>Test with: <code className="bg-secondary px-1 rounded">ssh -T git@github.com</code></li>
                </ol>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Permission denied error
                </p>
                <p>
                  If you get "Permission denied (publickey)":
                </p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Verify your SSH key is added to GitHub</li>
                  <li>Check that your private key permissions are correct (600)</li>
                  <li>Ensure you're using the correct key pair</li>
                  <li>Try adding your key to ssh-agent</li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};
