import React, { useState, useEffect } from 'react';
import { RefreshCw, ChevronDown, ChevronUp, Terminal, Copy, Check } from 'lucide-react';
import { HomebrewStatus, InstallResult } from '../../types';
import { useSetupWizard } from '../SetupWizardContext';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';
import { InstallResultMessage } from '../../settings/components/InstallResultMessage';
import { StatusBadge } from '../../settings/components/StatusBadge';
import homebrewIcon from '../../assets/homebrew-icon.png';

export const HomebrewSetupStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger, scrollToTop, setStepWorking } = useSetupWizard();
  const [homebrewStatus, setHomebrewStatus] = useState<HomebrewStatus>({
    installed: false,
    version: null,
    path: null,
    updateAvailable: false,
    latestVersion: null
  });
  const [installing, setInstalling] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [reinstalling, setReinstalling] = useState(false);
  const [refreshing, setRefreshing] = useState(true);
  const [installResult, setInstallResult] = useState<InstallResult | null>(null);
  const [showAboutStep, setShowAboutStep] = useState(false);
  const [showTroubleshooting, setShowTroubleshooting] = useState(false);
  const [installOutput, setInstallOutput] = useState<string>('');
  const [showInstallOutput, setShowInstallOutput] = useState(false);
  const [updateOutput, setUpdateOutput] = useState<string>('');
  const [showUpdateOutput, setShowUpdateOutput] = useState(false);
  const [reinstallOutput, setReinstallOutput] = useState<string>('');
  const [showReinstallOutput, setShowReinstallOutput] = useState(false);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [copiedOutput, setCopiedOutput] = useState<string | null>(null);
  const outputEndRef = React.useRef<HTMLDivElement>(null);

  const checkStatus = async (forceRefresh = false) => {
    try {
      const status = await window.setupWizardAPI.getHomebrewStatus(forceRefresh);
      setHomebrewStatus(status);

      // Refresh validation status
      await refreshStepStatus('homebrew-setup');
    } catch (error) {
      console.error('Failed to check Homebrew 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 handleInstall = async () => {
    setStepWorking('homebrew-setup', true);
    setInstalling(true);
    setInstallResult(null);
    setInstallOutput('');
    setShowInstallOutput(true);

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

    try {
      const result = await window.setupWizardAPI.installHomebrew();
      setInstallResult(result);

      if (result.success) {
        // Wait for UI to update before scrolling and refreshing
        setTimeout(() => {
          scrollToTop();
          checkStatus(true);
        }, 500);
      }
    } catch (error: any) {
      setInstallResult({
        success: false,
        message: error.message || 'Failed to install Homebrew'
      });
    } finally {
      setInstalling(false);
      setStepWorking('homebrew-setup', false);
      // Clean up listener
      cleanup();
    }
  };

  const handleUpdate = async () => {
    setStepWorking('homebrew-setup', true);
    setUpdating(true);
    setInstallResult(null);
    setUpdateOutput('');
    setShowUpdateOutput(true);

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

    try {
      const result = await window.setupWizardAPI.updateHomebrew();
      setInstallResult(result);

      if (result.success) {
        // Wait for UI to update before scrolling and refreshing
        setTimeout(() => {
          scrollToTop();
          checkStatus(true);
        }, 500);
      }
    } catch (error: any) {
      setInstallResult({
        success: false,
        message: error.message || 'Failed to update Homebrew'
      });
    } finally {
      setUpdating(false);
      setStepWorking('homebrew-setup', false);
      // Clean up listener
      cleanup();
    }
  };

  const handleReinstall = async () => {
    // Show confirmation dialog
    const confirmed = window.confirm(
      'Homebrew will be uninstalled and reinstalled.\n\n' +
      'Important: You will be prompted to authenticate using your macOS password.\n\n' +
      'This process may take several minutes. Continue?'
    );

    if (!confirmed) {
      return;
    }

    setStepWorking('homebrew-setup', true);
    setReinstalling(true);
    setInstallResult(null);
    setReinstallOutput('');
    setShowReinstallOutput(true);

    // Show info message about authentication
    setInstallResult({
      success: true,
      message: 'Starting reinstall... You will be prompted to authenticate.'
    });

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

    try {
      const result = await window.setupWizardAPI.reinstallHomebrew();
      setInstallResult(result);

      if (result.success) {
        // Wait for UI to update before scrolling and refreshing
        setTimeout(() => {
          scrollToTop();
          checkStatus(true);
        }, 500);
      }
    } catch (error: any) {
      setInstallResult({
        success: false,
        message: error.message || 'Failed to reinstall Homebrew'
      });
    } finally {
      setReinstalling(false);
      setStepWorking('homebrew-setup', false);
      // Clean up listener
      cleanup();
    }
  };

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

  const handleOpenTerminal = async () => {
    try {
      const result = await window.setupWizardAPI.openTerminal();
      if (!result.success) {
        setInstallResult({
          success: false,
          message: result.message || 'Failed to open Terminal'
        });
      }
    } catch (error: any) {
      setInstallResult({
        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">Ensure Homebrew is installed</p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || installing || updating || reinstalling}
            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 Homebrew?
                </p>
                <p>
                  Homebrew is the package manager for macOS. It allows you to easily install, update, and manage development tools and applications from the command line.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Canvas development requires several tools (Git, Docker, Ruby, Node.js, etc.) that are most easily installed and managed through Homebrew. It ensures all developers have consistent versions of these tools.
                </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 Homebrew is already installed on your system</li>
                  <li>Detects the installed version and installation path</li>
                  <li>Checks for available updates</li>
                  <li>Provides options to install, update, or reinstall Homebrew</li>
                  <li>Verifies the installation by running <code className="bg-muted px-1 rounded">brew --version</code></li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>

      {installResult && (
        <InstallResultMessage
          result={installResult}
          onDismiss={() => setInstallResult(null)}
        />
      )}

      {/* Homebrew Status Card */}
      <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={homebrewIcon}
              alt="Homebrew"
              className="w-full h-full object-cover"
            />
          </div>
          <div>
            <h3 className="text-[15px] font-semibold text-foreground">Homebrew</h3>
            <StatusBadge installed={homebrewStatus.installed} />
          </div>
        </div>

        {homebrewStatus.installed && homebrewStatus.version && (
          <div className="mb-4 text-sm">
            <span className="text-muted-foreground">Version: </span>
            <span
              className="font-medium"
              style={{
                color: homebrewStatus.updateAvailable
                  ? '#f97316'
                  : '#10b981'
              }}
            >
              {homebrewStatus.version}
              {homebrewStatus.updateAvailable && homebrewStatus.latestVersion
                ? ` (Latest: ${homebrewStatus.latestVersion})`
                : homebrewStatus.updateAvailable
                ? ' (Update available)'
                : ' (Latest)'}
            </span>
          </div>
        )}

        <div className="space-y-3">
          {!homebrewStatus.installed ? (
            <Alert variant="warning">
              <AlertDescription>
                <p className="font-medium mb-1">Homebrew Not Installed</p>
                <p className="text-xs">
                  Please install Homebrew manually by visiting{' '}
                  <a
                    href="https://brew.sh"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:text-blue-700 underline"
                  >
                    brew.sh
                  </a>
                  {' '}and following the installation instructions.
                </p>
              </AlertDescription>
            </Alert>
          ) : (
            <div className="space-y-2">
              {homebrewStatus.updateAvailable && (
                <Button
                  onClick={handleUpdate}
                  disabled={updating}
                  className="w-full"
                  variant="default"
                >
                  {updating ? 'Updating...' : 'Update Homebrew'}
                </Button>
              )}
            </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">
                  Installing Homebrew Manually
                </p>
                <ol className="list-decimal list-inside space-y-1">
                  <li>Open your terminal</li>
                  <li>
                    Visit{' '}
                    <a
                      href="https://brew.sh"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 underline hover:text-blue-700 dark:hover:text-blue-300"
                    >
                      https://brew.sh
                    </a>{' '}
                    and follow the installation instructions
                  </li>
                </ol>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Updating Homebrew Manually
                </p>
                <ol className="list-decimal list-inside space-y-2">
                  <li>Open your terminal</li>
                  <li className="flex items-start gap-2">
                    <span className="flex-1">
                      First, update Homebrew itself:
                      <div className="mt-1 flex items-center gap-2">
                        <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                          brew update
                        </code>
                        <button
                          onClick={() => handleCopyCode('brew update', 'brew-update')}
                          className="p-1 hover:bg-secondary rounded"
                          title="Copy to clipboard"
                        >
                          {copiedCode === 'brew-update' ? (
                            <Check className="h-3.5 w-3.5 text-green-600" />
                          ) : (
                            <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                          )}
                        </button>
                      </div>
                    </span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="flex-1">
                      Then, upgrade all installed packages:
                      <div className="mt-1 flex items-center gap-2">
                        <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                          brew upgrade
                        </code>
                        <button
                          onClick={() => handleCopyCode('brew upgrade', 'brew-upgrade')}
                          className="p-1 hover:bg-secondary rounded"
                          title="Copy to clipboard"
                        >
                          {copiedCode === 'brew-upgrade' ? (
                            <Check className="h-3.5 w-3.5 text-green-600" />
                          ) : (
                            <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                          )}
                        </button>
                      </div>
                    </span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="flex-1">
                      Or update just Homebrew without upgrading packages:
                      <div className="mt-1 flex items-center gap-2">
                        <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1">
                          brew update --auto-update
                        </code>
                        <button
                          onClick={() => handleCopyCode('brew update --auto-update', 'brew-auto-update')}
                          className="p-1 hover:bg-secondary rounded"
                          title="Copy to clipboard"
                        >
                          {copiedCode === 'brew-auto-update' ? (
                            <Check className="h-3.5 w-3.5 text-green-600" />
                          ) : (
                            <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                          )}
                        </button>
                      </div>
                    </span>
                  </li>
                </ol>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Uninstalling Homebrew Manually
                </p>
                <ol className="list-decimal list-inside space-y-2">
                  <li>Open your terminal</li>
                  <li className="flex items-start gap-2">
                    <span className="flex-1">
                      Run the command:
                      <div className="mt-1 flex items-center gap-2">
                        <code className="px-2 py-1 rounded text-xs bg-secondary text-foreground flex-1 break-all">
                          /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)"
                        </code>
                        <button
                          onClick={() => handleCopyCode('/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)"', 'brew-uninstall')}
                          className="p-1 hover:bg-secondary rounded flex-shrink-0"
                          title="Copy to clipboard"
                        >
                          {copiedCode === 'brew-uninstall' ? (
                            <Check className="h-3.5 w-3.5 text-green-600" />
                          ) : (
                            <Copy className="h-3.5 w-3.5 text-muted-foreground" />
                          )}
                        </button>
                      </div>
                    </span>
                  </li>
                </ol>
              </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>
      )}

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

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