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

export const ArtifactorySetupStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger } = useSetupWizard();
  const [status, setStatus] = useState<ArtifactoryStatus>({
    configured: false,
    gemrcExists: false
  });
  const [username, setUsername] = useState('');
  const [token, setToken] = useState('');
  const [saving, setSaving] = useState(false);
  const [refreshing, setRefreshing] = useState(true);
  const [result, setResult] = useState<InstallResult | null>(null);
  const [showAboutStep, setShowAboutStep] = useState(false);
  const [showInstructions, setShowInstructions] = useState(false);
  const [showTroubleshooting, setShowTroubleshooting] = useState(false);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

  const checkStatus = async (forceRefresh = false) => {
    try {
      const artifactoryStatus = await window.setupWizardAPI.getArtifactoryStatus(forceRefresh);
      setStatus(artifactoryStatus);

      if (artifactoryStatus.username) {
        setUsername(artifactoryStatus.username);
      }

      if (artifactoryStatus.token) {
        setToken(artifactoryStatus.token);
      }

      // Refresh validation status
      await refreshStepStatus('artifactory-setup');
    } catch (error) {
      console.error('Failed to check Artifactory 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 handleRefresh = async () => {
    setRefreshing(true);
    setResult(null);
    await checkStatus(true); // Force refresh
    setRefreshing(false);
  };

  const handleOpenInFinder = async () => {
    // Use tilde path - the main process will expand it to the home directory
    const gemrcPath = '~/.gemrc';
    try {
      const success = await window.setupWizardAPI.showInFinder(gemrcPath);
      if (!success) {
        setResult({
          success: false,
          message: 'Failed to open .gemrc in Finder'
        });
      }
    } catch (error) {
      console.error('Error opening .gemrc in Finder:', error);
      setResult({
        success: false,
        message: 'Failed to open .gemrc in Finder'
      });
    }
  };

  const handleSave = async () => {
    if (!username.trim() || !token.trim()) {
      setResult({
        success: false,
        message: 'Please enter both username and identity token'
      });
      return;
    }

    setSaving(true);
    setResult(null);

    try {
      const setupResult = await window.setupWizardAPI.setupArtifactory({
        username: username.trim(),
        token: token.trim(),
        overwrite: true
      });

      setResult(setupResult);

      if (setupResult.success) {
        // Don't clear token - keep it visible for user reference
        // Force refresh status to validate credentials
        await checkStatus(true);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to save configuration'
      });
    } finally {
      setSaving(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);
    }
  };
  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 JFrog Artifactory credentials</p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || saving}
            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 JFrog Artifactory?
                </p>
                <p>
                  JFrog Artifactory is Instructure's private gem repository that hosts internal Ruby gems required for Canvas development.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Canvas depends on proprietary gems that aren't available on public RubyGems. You need authenticated access to download these gems during the build process.
                </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>Checks if ~/.gemrc file exists and contains Artifactory credentials</li>
                  <li>Validates your username and identity token with Artifactory</li>
                  <li>Allows you to configure or update your credentials</li>
                  <li>Saves credentials to ~/.gemrc in the format required by RubyGems</li>
                  <li>Saves the auth token to ~/.npmrc for pnpm @inst registry access</li>
                  <li>Verifies authentication by testing access to the gem repository</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={jfrogIcon} alt="JFrog" className="w-full h-full object-cover" />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">
                JFrog Artifactory
              </h3>
              <div className="mt-1">
                {status.configured && status.credentialsValid ? (
                  <Badge variant="success" className="text-xs">
                    <CheckCircle2 className="h-3.5 w-3.5 mr-1" />
                    Configured
                  </Badge>
                ) : status.configured && status.credentialsValid === false ? (
                  <Badge variant="warning" className="text-xs">
                    <AlertCircle className="h-3.5 w-3.5 mr-1" />
                    Invalid Credentials
                  </Badge>
                ) : (
                  <Badge variant="warning" className="text-xs">
                    <AlertCircle className="h-3.5 w-3.5 mr-1" />
                    Not Configured
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </div>

        {status.configured && status.credentialsValid && (
          <Alert variant="success" className="mb-4">
            <CheckCircle2 className="h-5 w-5" />
            <AlertDescription>
              <p className="font-medium mb-1">Artifactory is configured</p>
              <p className="text-xs">
                Your <code className="bg-green-100 dark:bg-green-900/30 px-1 rounded">~/.gemrc</code> and{' '}
                <code className="bg-green-100 dark:bg-green-900/30 px-1 rounded">~/.npmrc</code> files
                are configured with valid credentials.
              </p>
            </AlertDescription>
          </Alert>
        )}

        {status.gemrcExists && status.credentialsValid && !status.npmrcConfigured && (
          <Alert variant="warning" className="mb-4">
            <AlertCircle className="h-5 w-5" />
            <AlertDescription>
              <p className="font-medium mb-1">~/.npmrc not configured</p>
              <p className="text-xs">
                Your <code className="bg-yellow-100 dark:bg-yellow-900/30 px-1 rounded">~/.gemrc</code> is valid,
                but <code className="bg-yellow-100 dark:bg-yellow-900/30 px-1 rounded">~/.npmrc</code> is missing
                the @inst registry. Re-save your credentials below to fix this.
              </p>
            </AlertDescription>
          </Alert>
        )}

        {status.configured && status.credentialsValid === false && (
          <Alert variant="warning" className="mb-4">
            <AlertCircle className="h-5 w-5" />
            <AlertDescription>
              <p className="font-medium mb-1">Invalid Artifactory credentials</p>
              <p className="text-xs">
                Your <code className="bg-yellow-100 dark:bg-yellow-900/30 px-1 rounded">~/.gemrc</code> file
                is configured, but the credentials are not valid.
                {status.credentialsValidationError && ` (${status.credentialsValidationError})`}
              </p>
              <p className="text-xs mt-2">
                Please update your username and identity token below.
              </p>
            </AlertDescription>
          </Alert>
        )}

        <div className="space-y-4">
          {!status.configured && (
            <p className="text-[13px] text-muted-foreground">
              Configure your JFrog Artifactory credentials to access internal gems.
              This will create or update your <code className="bg-muted px-1 rounded">~/.gemrc</code> file
              and save the auth token to <code className="bg-muted px-1 rounded">~/.npmrc</code> for pnpm.
            </p>
          )}

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

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">JFrog Username</Label>
              <Input
                id="username"
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="your.email@instructure.com"
               
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="token">Identity Token</Label>
              <Input
                id="token"
                type="password"
                value={token}
                onChange={(e) => setToken(e.target.value)}
                placeholder="Enter your identity token"
               
              />
            </div>

            <div className="flex gap-2">
              <Button
                onClick={handleSave}
                disabled={saving || !username.trim() || !token.trim()}
                className="flex-1"
              >
                {saving ? 'Saving...' : 'Save Configuration'}
              </Button>

              {status.gemrcExists && (
                <Button
                  onClick={handleOpenInFinder}
                  variant="outline"
                  disabled={saving}
                >
                  <FolderOpen className="h-4 w-4 mr-2" />
                  Open in Finder
                </Button>
              )}
            </div>

            {status.configured && (
              <a
                href="https://instructure.jfrog.io/ui/user_profile"
                target="_blank"
                rel="noopener noreferrer"
                className="block text-center text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
              >
                Reconfigure credentials
              </a>
            )}
          </div>

          <div className="border-t border-border pt-4">
            <button
              onClick={() => setShowInstructions(!showInstructions)}
              className="flex items-center gap-2 text-sm w-full text-foreground hover:opacity-80"
            >
              {showInstructions ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
              How to get your identity token
            </button>

            {showInstructions && (
              <div className="mt-3 p-4 rounded-lg text-sm space-y-3 bg-muted text-muted-foreground">
                <ol className="list-decimal list-inside space-y-2">
                  <li>
                    Visit{' '}
                    <a
                      href="https://instructure.jfrog.io/ui/user_profile"
                      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"
                    >
                      JFrog User Profile
                      <ExternalLink className="h-3 w-3" />
                    </a>
                  </li>
                  <li>Your JFrog Username can be found on the User Profile Page right after the "User Profile:" string</li>
                  <li>Click on "Generate Identity Token" or use an existing token</li>
                  <li>Copy the token (it will only be shown once)</li>
                  <li>Paste the username and token into the fields above</li>
                </ol>

                <div className="space-y-2 mt-3">
                  <p className="text-xs text-muted-foreground">
                    <strong>Note:</strong> Your credentials will be stored in{' '}
                    <code className="bg-card px-1 rounded">~/.gemrc</code> on your
                    local machine.
                  </p>
                  <p className="text-xs text-muted-foreground">
                    <strong>Note:</strong> If you don't have access to JFrog from Okta, you need to 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 with your manager's approval.
                  </p>
                </div>
              </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">
                  Invalid credentials error
                </p>
                <p>
                  If you see "Invalid credentials" after saving:
                </p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Verify your username is correct (usually your email)</li>
                  <li>Generate a new identity token from JFrog</li>
                  <li>Make sure you copied the entire token without extra spaces</li>
                  <li>Check if your JFrog account is active</li>
                </ul>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Manually checking .gemrc file
                </p>
                <p>
                  To view your .gemrc configuration:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    cat ~/.gemrc
                  </code>
                  <button
                    onClick={() => handleCopyCode('cat ~/.gemrc', 'cat-gemrc')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'cat-gemrc' ? (
                      <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">
                  The file should contain your Artifactory URL and credentials.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Testing Artifactory access
                </p>
                <p>
                  Test if you can access Artifactory gems:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    gem list --remote --source https://instructure.jfrog.io/artifactory/api/gems/gems
                  </code>
                  <button
                    onClick={() => handleCopyCode('gem list --remote --source https://instructure.jfrog.io/artifactory/api/gems/gems', 'gem-list')}
                    className="p-1 hover:bg-secondary rounded flex-shrink-0"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'gem-list' ? (
                      <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">
                  No access to JFrog
                </p>
                <p>
                  If you don't have JFrog access via Okta, file an{' '}
                  <a
                    href="https://iops.instructure.com"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 dark:text-blue-400 underline hover:text-blue-700 dark:hover:text-blue-300"
                  >
                    iops.instructure.com
                  </a>
                  {' '}ticket with your manager's approval requesting JFrog Artifactory access.
                </p>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};
