import React, { useState, useEffect } from 'react';
import { CheckCircle2, AlertCircle, RefreshCw, ChevronDown, ChevronUp, Terminal, Copy, Check } from 'lucide-react';
import { GitConfigStatus, 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 { StatusBadge } from '../../settings/components/StatusBadge';
import gitIcon from '../../assets/git-icon.png';

export const GitSetupStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger, setStepWorking } = useSetupWizard();
  const [status, setStatus] = useState<GitConfigStatus>({
    gitInstalled: false,
    gitconfigExists: false
  });
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [saving, setSaving] = 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 [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [copiedOutput, setCopiedOutput] = useState<string | null>(null);
  const [installing, setInstalling] = useState(false);
  const [installOutput, setInstallOutput] = useState<string>('');
  const [showInstallOutput, setShowInstallOutput] = useState(false);
  const outputEndRef = React.useRef<HTMLDivElement>(null);

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

      if (gitStatus.name) {
        setName(gitStatus.name);
      }

      if (gitStatus.email) {
        setEmail(gitStatus.email);
      }

      // Refresh validation status
      await refreshStepStatus('git-setup');
    } catch (error) {
      console.error('Failed to check Git 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 handleSave = async () => {
    if (!status.gitInstalled) {
      setResult({
        success: false,
        message: 'Git command not found. Please install Git first.'
      });
      return;
    }

    if (!name.trim() || !email.trim()) {
      setResult({
        success: false,
        message: 'Please enter both name and email'
      });
      return;
    }

    setSaving(true);
    setResult(null);

    try {
      const saveResult = await window.setupWizardAPI.updateGitConfig({
        name: name.trim(),
        email: email.trim()
      });

      setResult(saveResult);

      if (saveResult.success) {
        // Refresh status
        await checkStatus(true); // Force refresh
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to save configuration'
      });
    } finally {
      setSaving(false);
    }
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    setResult(null);
    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 handleInstall = async () => {
    setStepWorking('git-setup', true);
    setInstalling(true);
    setResult(null);
    setInstallOutput('');
    setShowInstallOutput(true);

    // Set up listener for install output
    const cleanup = window.setupWizardAPI.onInstallGitOutput((output) => {
      setInstallOutput((prev) => prev + output);
      // Auto-scroll to bottom
      setTimeout(() => {
        outputEndRef.current?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    });

    try {
      const installResult = await window.setupWizardAPI.installGit();
      setResult(installResult);

      if (installResult.success) {
        // Wait for UI to update before refreshing
        setTimeout(() => {
          checkStatus(true);
        }, 500);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to install Git'
      });
    } finally {
      setInstalling(false);
      setStepWorking('git-setup', false);
      // Clean up listener
      cleanup();
    }
  };

  const isConfigured = status.gitInstalled && status.gitconfigExists && status.name && status.email;

  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 Git user name and email</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 Git configuration?
                </p>
                <p>
                  Git uses your name and email to identify you as the author of commits. This information is embedded in every commit you make and is visible in the repository history.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Canvas development involves making commits to track changes. Having your name and email configured ensures proper attribution of your work and helps team members identify who made specific changes.
                </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 Git is installed on your system</li>
                  <li>Reads your current Git configuration from <code className="bg-muted px-1 rounded">~/.gitconfig</code></li>
                  <li>Displays your configured name and email if present</li>
                  <li>Allows you to set or update your Git user name and email</li>
                  <li>Saves the configuration globally using <code className="bg-muted px-1 rounded">git config --global</code></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 gap-3 mb-4">
          <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">Git</h3>
            <StatusBadge installed={status.gitInstalled} />
          </div>
        </div>

        {status.gitInstalled && status.version && (
          <div className="mb-4 text-sm">
            <span className="text-muted-foreground">Version: </span>
            <span
              className="font-medium"
              style={{ color: '#10b981' }}
            >
              {status.version}
            </span>
          </div>
        )}

        {!status.gitInstalled && (
          <div className="space-y-4 mb-4">
            <Alert variant="destructive">
              <AlertCircle className="h-5 w-5" />
              <AlertDescription>
                <p className="font-medium mb-1">Git Not Installed</p>
                <p className="text-xs">
                  Git is not installed on your system. Click the button below to install it via Homebrew.
                </p>
              </AlertDescription>
            </Alert>

            <Button
              onClick={handleInstall}
              disabled={installing}
              className="w-full h-10 bg-[#007AFF] hover:bg-[#0066DD] text-white text-[13px] font-medium"
            >
              {installing ? (
                <>
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  Installing...
                </>
              ) : (
                'Install Git via Homebrew'
              )}
            </Button>
          </div>
        )}

        {isConfigured && (
          <Alert variant="success" className="mb-4">
            <CheckCircle2 className="h-5 w-5" />
            <AlertDescription>
              <p className="font-medium mb-1">Git is configured</p>
              <p className="text-xs">
                Your <code className="bg-green-100 dark:bg-green-900/30 px-1 rounded">~/.gitconfig</code> file
                is configured with your user name and email.
              </p>
            </AlertDescription>
          </Alert>
        )}

        <div className="space-y-4">
          {status.gitInstalled && !isConfigured && (
            <p className="text-[13px] text-muted-foreground">
              Configure your Git user name and email. This information will be used
              to identify your commits.
            </p>
          )}

          {status.gitInstalled && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">Name</Label>
                <Input
                  id="name"
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Your Name"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="your.email@example.com"
                />
              </div>

              <Button
                onClick={handleSave}
                disabled={saving || !name.trim() || !email.trim()}
                className="w-full"
              >
                {saving ? 'Saving...' : 'Save Configuration'}
              </Button>

              {isConfigured && (
                <p className="text-xs text-center text-muted-foreground">
                  Update your name or email and click Save to change your Git configuration
                </p>
              )}
            </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">
                  Git command not found
                </p>
                <p>
                  If Git is not installed, install it using Homebrew:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    brew install git
                  </code>
                  <button
                    onClick={() => handleCopyCode('brew install git', 'brew-install-git')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'brew-install-git' ? (
                      <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>
                  Or install it using xcode command line tools:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    xcode-select --install
                  </code>
                  <button
                    onClick={() => handleCopyCode('xcode-select --install', 'xcode-select-install')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'xcode-select-install' ? (
                      <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">
                  After installing, close and reopen your terminal, then click the Refresh Status button.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Verifying Git configuration
                </p>
                <p>
                  To manually check your Git configuration, run:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    git config --global user.name
                  </code>
                  <button
                    onClick={() => handleCopyCode('git config --global user.name', 'git-config-name')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'git-config-name' ? (
                      <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">
                    git config --global user.email
                  </code>
                  <button
                    onClick={() => handleCopyCode('git config --global user.email', 'git-config-email')}
                    className="p-1 hover:bg-secondary rounded"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'git-config-email' ? (
                      <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">
                  Manually configuring Git
                </p>
                <p>
                  If you prefer to configure Git manually via terminal:
                </p>
                <div className="flex items-center gap-2">
                  <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                    git config --global user.name "Your Name"
                  </code>
                  <button
                    onClick={() => handleCopyCode('git config --global user.name "Your Name"', 'git-set-name')}
                    className="p-1 hover:bg-secondary rounded flex-shrink-0"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'git-set-name' ? (
                      <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">
                    git config --global user.email "your.email@example.com"
                  </code>
                  <button
                    onClick={() => handleCopyCode('git config --global user.email "your.email@example.com"', 'git-set-email')}
                    className="p-1 hover:bg-secondary rounded flex-shrink-0"
                    title="Copy to clipboard"
                  >
                    {copiedCode === 'git-set-email' ? (
                      <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>

      {showInstallOutput && (
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-foreground">Install Output</h4>
            <div className="flex items-center gap-1">
              <button
                onClick={() => { navigator.clipboard.writeText(installOutput); setCopiedOutput('install'); setTimeout(() => setCopiedOutput(null), 2000); }}
                className="p-1 hover:bg-secondary rounded"
                title="Copy output"
              >
                {copiedOutput === 'install' ? <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={() => setShowInstallOutput(false)}
                variant="ghost"
                size="sm"
                disabled={installing}
              >
                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' }}
          >
            {installOutput || 'Waiting for output...'}
            <div ref={outputEndRef} />
          </div>
        </Card>
      )}
    </div>
  );
};
