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 gerritIcon from '../../assets/gerrit-icon.png';

export const GerritSetupStep: 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 [username, setUsername] = useState<string>('');
  const [verifying, setVerifying] = useState(false);
  const [usernameFromConfig, setUsernameFromConfig] = useState(false);

  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('gerrit-setup');

      // Check if this step is now completed and load saved username
      const onboardingState = await window.setupWizardAPI.getState();
      const stepData = onboardingState.stepStatus['gerrit-setup'];
      setCompleted(stepData?.completed || false);

      // Load saved username if exists in step data
      if (stepData?.data?.username) {
        setUsername(stepData.data.username);
        setUsernameFromConfig(false);
      } else {
        // Try to retrieve username from SSH config
        const configUsername = await window.setupWizardAPI.getGerritUsername();
        if (configUsername) {
          setUsername(configUsername);
          setUsernameFromConfig(true);
        }
      }
    } catch (error) {
      console.error('Failed to check Gerrit 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 handleVerify = async () => {
    if (!username.trim()) {
      setResult({
        success: false,
        message: 'Please enter your Gerrit username'
      });
      return;
    }

    if (!sshKeyStatus?.privateKeyPath) {
      setResult({
        success: false,
        message: 'SSH key not found'
      });
      return;
    }

    setVerifying(true);
    setResult(null);

    try {
      // Update SSH config with username
      const configResult = await window.setupWizardAPI.updateGerritSshConfig(
        sshKeyStatus.privateKeyPath,
        username.trim()
      );

      if (!configResult.success) {
        setResult(configResult);
        return;
      }

      // Test SSH connection
      const connectionTest = await window.setupWizardAPI.testGerritConnection(
        sshKeyStatus.privateKeyPath
      );

      if (connectionTest.success) {
        // Save username to step data
        const currentState = await window.setupWizardAPI.getState();
        const updatedState = {
          ...currentState,
          stepStatus: {
            ...currentState.stepStatus,
            'gerrit-setup': {
              ...currentState.stepStatus['gerrit-setup'],
              completed: true,
              data: {
                ...currentState.stepStatus['gerrit-setup']?.data,
                username: username.trim()
              }
            }
          }
        };
        await window.setupWizardAPI.setState(updatedState);

        // Refresh status
        await checkStatus(true);

        setResult({
          success: true,
          message: 'Gerrit SSH connection verified and configured successfully'
        });
      } else {
        setResult(connectionTest);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to verify Gerrit connection'
      });
    } finally {
      setVerifying(false);
    }
  };

  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 Gerrit 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 Gerrit?
                </p>
                <p>
                  Gerrit is Instructure's primary code review system where the Canvas LMS source code is hosted. It provides Git repository hosting with integrated code review workflows, enabling collaborative development with peer reviews before code is merged.
                </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 Gerrit enables secure, passwordless authentication when cloning Canvas repositories, pushing code changes, and submitting patches for review. Without proper SSH configuration, you won't be able to interact with Canvas repositories or contribute code.
                </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 Gerrit 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; gerrit.instructure.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={gerritIcon} alt="Gerrit" className="w-full h-full object-cover" />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">
                Gerrit
              </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 Gerrit to access Canvas 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="space-y-2">
                <Label>Gerrit Username</Label>
                <p className="text-xs text-muted-foreground mb-2">
                  Enter your Gerrit username from{' '}
                  <a
                    href="https://gerrit.instructure.com/settings/#SSHKeys"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                  >
                    Gerrit SSH Keys Settings
                  </a>
                </p>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={username}
                    onChange={(e) => {
                      setUsername(e.target.value);
                      setUsernameFromConfig(false);
                    }}
                    placeholder="Enter Gerrit username"
                    disabled={verifying || completed}
                    className="flex-1 px-3 py-2 text-sm rounded border bg-background text-foreground disabled:opacity-50"
                  />
                  <Button
                    onClick={handleVerify}
                    disabled={verifying || !username.trim() || completed}
                    variant="default"
                    size="sm"
                  >
                    {verifying ? 'Verifying...' : 'Verify'}
                  </Button>
                </div>
                {usernameFromConfig && !result && (
                  <p className="text-xs text-muted-foreground">
                    Username retrieved from <code className="bg-muted px-1 rounded">~/.ssh/config</code>
                  </p>
                )}
                {result && (
                  <Alert variant={result.success ? "success" : "destructive"}>
                    <AlertDescription className="text-xs">
                      {result.message}
                    </AlertDescription>
                  </Alert>
                )}
              </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 Gerrit
                </p>
                <ol className="list-decimal list-inside space-y-2">
                  <li>
                    Go to{' '}
                    <a
                      href="https://gerrit.instructure.com/settings/#SSHKeys"
                      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"
                    >
                      Gerrit SSH Keys Settings
                      <ExternalLink className="h-3 w-3" />
                    </a>
                  </li>
                  <li>Sign in using Okta (if needed)</li>
                  <li>
                    Add an SSH key: copy the contents of your public key to the text field "New SSH key"
                  </li>
                </ol>

                <p className="text-xs mt-3 text-muted-foreground">
                  <strong>Note:</strong> Ask your team lead if you don't have access to the repos you need.
                  They may need to have you file an{' '}
                  <a
                    href="https://iops.instructure.com"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                  >
                    iops.instructure.com
                  </a>
                  {' '}ticket w/ your manager's approval.
                </p>
              </div>

              {completed ? (
                <Alert variant="success">
                  <CheckCircle2 className="h-5 w-5" />
                  <AlertDescription>
                    <p className="font-medium mb-1">Gerrit SSH connection verified</p>
                    <p className="text-xs">
                      Your SSH key is properly configured with Gerrit. You can now access Canvas 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 Gerrit, 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 Gerrit
                </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 gerrit.instructure.com`
                      : 'ssh -T gerrit.instructure.com'}
                  </code>
                  <button
                    onClick={() => handleCopyCode(
                      sshKeyStatus?.privateKeyPath
                        ? `ssh -T -i "${sshKeyStatus.privateKeyPath}" -o IdentitiesOnly=yes gerrit.instructure.com`
                        : 'ssh -T gerrit.instructure.com',
                      'ssh-gerrit'
                    )}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'ssh-gerrit' ? (
                      <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. 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>
                  Gerrit 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 Gerrit
                </p>
                <ol className="list-decimal list-inside space-y-1">
                  <li>Visit{' '}
                    <a
                      href="https://gerrit.instructure.com/settings/#SSHKeys"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 underline hover:text-blue-700 dark:hover:text-blue-300"
                    >
                      Gerrit SSH Keys
                    </a>
                  </li>
                  <li>Click "Add SSH Key"</li>
                  <li>Paste your public key</li>
                  <li>Test with: <code className="bg-secondary px-1 rounded">ssh -T gerrit.instructure.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 Gerrit</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>
  );
};
