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

export const SshKeysSetupStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger } = useSetupWizard();
  const [status, setStatus] = useState<SshKeyStatus>({
    keysExist: false,
    valid: false
  });
  const [filename, setFilename] = useState('id_ed25519');
  const [passphrase, setPassphrase] = useState('');
  const [generating, setGenerating] = useState(false);
  const [refreshing, setRefreshing] = useState(true);
  const [result, setResult] = useState<InstallResult | null>(null);
  const [showAboutStep, setShowAboutStep] = useState(false);
  const [showTroubleshooting, setShowTroubleshooting] = useState(false);
  const [copied, setCopied] = useState(false);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

  const checkStatus = async (publicKeyPath?: string, forceRefresh = false) => {
    try {
      const sshStatus = await window.setupWizardAPI.getSshKeyStatus(publicKeyPath, forceRefresh);
      setStatus(sshStatus);

      // Refresh validation status
      await refreshStepStatus('ssh-keys-setup');
    } catch (error) {
      console.error('Failed to check SSH key status:', error);
    } finally {
    }
  };

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

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

  const handleSelectKey = async () => {
    try {
      const fileResult = await window.setupWizardAPI.selectPublicKeyFile();

      if (fileResult && fileResult.filePath) {
        setRefreshing(true);

        // Show what happened with the keys
        setResult({
          success: true,
          message: fileResult.message || 'SSH keys configured successfully'
        });

        // Check status to update UI
        await checkStatus(fileResult.filePath, true);

        // Refresh Gerrit and GitHub steps since they depend on SSH keys
        await refreshStepStatus('gerrit-setup');
        await refreshStepStatus('github-setup');

        setRefreshing(false);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to select key file'
      });
      setRefreshing(false);
    }
  };

  const handleGenerate = async () => {
    if (!filename.trim()) {
      setResult({
        success: false,
        message: 'Please enter a filename for the SSH key'
      });
      return;
    }

    setGenerating(true);
    setResult(null);

    try {
      const generateResult = await window.setupWizardAPI.generateSshKeys({
        filename: filename.trim(),
        passphrase: passphrase
      });

      setResult(generateResult);

      if (generateResult.success) {
        // Refresh status after generation (force refresh to bypass cache)
        await checkStatus(undefined, true);

        // Refresh Gerrit and GitHub steps since they depend on SSH keys
        await refreshStepStatus('gerrit-setup');
        await refreshStepStatus('github-setup');
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to generate SSH keys'
      });
    } finally {
      setGenerating(false);
    }
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    setResult(null);
    await checkStatus(status.publicKeyPath, true); // Force refresh
    setRefreshing(false);
  };

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

  const handleFixConfig = async () => {
    if (!status.privateKeyPath) {
      setResult({
        success: false,
        message: 'Private key path not found'
      });
      return;
    }

    try {
      setRefreshing(true);
      const result = await window.setupWizardAPI.updateSshConfig(status.privateKeyPath);
      setResult(result);

      if (result.success) {
        // Refresh status to update UI
        await checkStatus(status.publicKeyPath, true);

        // Refresh Gerrit and GitHub steps since they depend on SSH config
        await refreshStepStatus('gerrit-setup');
        await refreshStepStatus('github-setup');
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to update SSH config'
      });
    } finally {
      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 isConfigured = status.keysExist && status.valid;

  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">
            Configure SSH keys for Git authentication
          </p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || generating}
            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 are SSH Keys?
                </p>
                <p>
                  SSH keys are cryptographic key pairs (public and private) used for secure authentication with Git repositories without passwords.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Canvas repositories on Gerrit and GitHub require SSH key authentication. SSH keys provide secure, password-less access and are required for git operations (clone, push, pull).
                </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>Scans ~/.ssh/ directory for existing SSH key pairs</li>
                  <li>Displays available keys (id_rsa, id_ed25519, etc.)</li>
                  <li>Allows you to select an existing key pair</li>
                  <li>Provides option to generate new SSH keys using ssh-keygen</li>
                  <li>Automatically configures ~/.ssh/config for GitHub and Gerrit</li>
                  <li>Sets proper file permissions (directory: 700, private key: 600, public key: 644)</li>
                  <li>Shows your public key for copying to Git services</li>
                  <li>Verifies key format and permissions</li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>

      {result && (
        <Alert variant={result.success ? "success" : "destructive"}>
          <AlertDescription className="text-xs">
            {result.message}
          </AlertDescription>
        </Alert>
      )}

      <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={sshKeysIcon} alt="SSH Keys" className="w-full h-full object-cover" />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">
                SSH Keys
              </h3>
              <div className="mt-1">
                {isConfigured ? (
                  <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>

        {isConfigured ? (
          <div className="space-y-4">
            <Alert variant="success">
              <CheckCircle2 className="h-5 w-5" />
              <AlertDescription>
                <p className="font-medium mb-1">SSH keys are configured</p>
                <p className="text-xs">
                  Public key: <code className="bg-green-100 dark:bg-green-900/30 px-1 rounded text-green-800 dark:text-green-200">{status.publicKeyPath}</code>
                </p>
              </AlertDescription>
            </Alert>

            {/* SSH Config Status */}
            {status.configExists ? (
              <Alert variant={status.configCorrect ? "success" : "default"}>
                {status.configCorrect ? (
                  <CheckCircle2 className="h-5 w-5" />
                ) : (
                  <AlertCircle className="h-5 w-5" />
                )}
                <AlertDescription>
                  <p className="font-medium mb-1">SSH Config (~/.ssh/config)</p>
                  <div className="text-xs space-y-1">
                    <div className="flex items-center gap-2">
                      <span>GitHub:</span>
                      {status.githubCorrect ? (
                        <span className="text-green-600">✓ Configured</span>
                      ) : (
                        <span className="text-orange-600">⚠ Needs update</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      <span>Gerrit:</span>
                      {status.gerritCorrect ? (
                        <span className="text-green-600">✓ Configured</span>
                      ) : (
                        <span className="text-orange-600">⚠ Needs update</span>
                      )}
                    </div>
                    {!status.configCorrect && (
                      <div className="mt-3">
                        <Button
                          onClick={handleFixConfig}
                          disabled={refreshing}
                          size="sm"
                          variant="outline"
                        >
                          {refreshing ? 'Updating...' : 'Fix SSH Config'}
                        </Button>
                      </div>
                    )}
                  </div>
                </AlertDescription>
              </Alert>
            ) : (
              <Alert variant="warning">
                <AlertCircle className="h-5 w-5" />
                <AlertDescription>
                  <p className="font-medium mb-1">SSH Config Missing</p>
                  <p className="text-xs mb-3">
                    The ~/.ssh/config file doesn't exist or is missing GitHub/Gerrit configuration.
                  </p>
                  <Button
                    onClick={handleFixConfig}
                    disabled={refreshing}
                    size="sm"
                    variant="outline"
                  >
                    {refreshing ? 'Creating...' : 'Create SSH Config'}
                  </Button>
                </AlertDescription>
              </Alert>
            )}

            {status.publicKeyContent && (
              <div className="space-y-2">
                <Label>Public Key</Label>
                <div className="relative">
                  <textarea
                    readOnly
                    value={status.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>
            )}

            <Button onClick={handleSelectKey} variant="outline" className="w-full">
              Select Different Key
            </Button>
          </div>
        ) : (
          <div className="space-y-4">
            <p className="text-[13px] text-muted-foreground">
              SSH keys are required for authenticating with Git repositories. You can either select
              an existing key pair or generate a new one.
            </p>

            <Alert variant="default" className="text-xs">
              <AlertDescription>
                <p className="font-medium mb-1">When selecting an existing key:</p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Both public and private keys will be copied to <code className="bg-secondary px-1 rounded">~/.ssh/</code></li>
                  <li>Proper permissions will be set (private: 600, public: 644, directory: 700)</li>
                  <li>SSH config (<code className="bg-secondary px-1 rounded">~/.ssh/config</code>) will be updated for GitHub and Gerrit</li>
                  <li>If the key is already in <code className="bg-secondary px-1 rounded">~/.ssh/</code>, it won't be overwritten (only permissions updated)</li>
                  <li>Keys from other locations will be copied to <code className="bg-secondary px-1 rounded">~/.ssh/</code> (may overwrite if same filename exists)</li>
                </ul>
              </AlertDescription>
            </Alert>

            <div className="space-y-3">
              <Button onClick={handleSelectKey} className="w-full">
                Select Existing SSH Key
              </Button>

              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <span className="w-full border-t border-border" />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="px-2 bg-secondary text-muted-foreground">
                    Or generate new keys
                  </span>
                </div>
              </div>

              <div className="space-y-3">
                <div className="space-y-2">
                  <Label htmlFor="filename">Key Filename</Label>
                  <Input
                    id="filename"
                    type="text"
                    value={filename}
                    onChange={(e) => setFilename(e.target.value)}
                    placeholder="id_ed25519"
                   
                  />
                  <p className="text-xs text-muted-foreground">
                    Keys will be saved to ~/.ssh/
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="passphrase">Passphrase (optional but recommended)</Label>
                  <Input
                    id="passphrase"
                    type="password"
                    value={passphrase}
                    onChange={(e) => setPassphrase(e.target.value)}
                    placeholder="Enter a secure passphrase"
                   
                  />
                </div>

                <Button
                  onClick={handleGenerate}
                  disabled={generating || !filename.trim()}
                  className="w-full"
                >
                  {generating ? (
                    <>
                      <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      Generating...
                    </>
                  ) : (
                    'Generate SSH Keys'
                  )}
                </Button>
              </div>
            </div>
          </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">
                  SSH key permissions issues
                </p>
                <p>
                  SSH keys must have correct permissions. Fix with:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    chmod 700 ~/.ssh
                  </code>
                  <button
                    onClick={() => handleCopyCode('chmod 700 ~/.ssh', 'chmod-ssh-dir')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'chmod-ssh-dir' ? (
                      <Check className="h-3.5 w-3.5 text-green-600" />
                    ) : (
                      <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                    )}
                  </button>
                </div>
                <div className="flex items-center gap-2 mt-1">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    chmod 600 ~/.ssh/id_ed25519
                  </code>
                  <button
                    onClick={() => handleCopyCode('chmod 600 ~/.ssh/id_ed25519', 'chmod-private-key')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'chmod-private-key' ? (
                      <Check className="h-3.5 w-3.5 text-green-600" />
                    ) : (
                      <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                    )}
                  </button>
                </div>
                <div className="flex items-center gap-2 mt-1">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    chmod 644 ~/.ssh/id_ed25519.pub
                  </code>
                  <button
                    onClick={() => handleCopyCode('chmod 644 ~/.ssh/id_ed25519.pub', 'chmod-public-key')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'chmod-public-key' ? (
                      <Check className="h-3.5 w-3.5 text-green-600" />
                    ) : (
                      <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                    )}
                  </button>
                </div>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Testing SSH connection to Gerrit
                </p>
                <p>
                  Verify your SSH key works with Gerrit:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    ssh -T gerrit.instructure.com
                  </code>
                  <button
                    onClick={() => handleCopyCode('ssh -T gerrit.instructure.com', 'ssh-gerrit-test')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'ssh-gerrit-test' ? (
                      <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 a welcome message if authentication is successful.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Testing SSH connection to GitHub
                </p>
                <p>
                  Verify your SSH key works with GitHub:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    ssh -T git@github.com
                  </code>
                  <button
                    onClick={() => handleCopyCode('ssh -T git@github.com', 'ssh-github-test')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'ssh-github-test' ? (
                      <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 a message like "Hi username! You've successfully authenticated..."
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Adding SSH key to ssh-agent
                </p>
                <p>
                  If you used a passphrase, add your key to ssh-agent:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    ssh-add ~/.ssh/id_ed25519
                  </code>
                  <button
                    onClick={() => handleCopyCode('ssh-add ~/.ssh/id_ed25519', 'ssh-add-key')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'ssh-add-key' ? (
                      <Check className="h-3.5 w-3.5 text-green-600" />
                    ) : (
                      <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                    )}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};
