import React, { useState, useEffect } from 'react';
import { RefreshCw, CheckCircle, AlertCircle, Copy, Check } from 'lucide-react';
import { SystemStatus, InstallResult, OnboardingState } from '../types';
import { DockerStatusCard } from './components/DockerStatusCard';
import { HomebrewStatusCard } from './components/HomebrewStatusCard';
import { InstallResultMessage } from './components/InstallResultMessage';
import { StatusCardSkeleton } from './components/StatusCardSkeleton';
import { Button } from '../components/ui/button';

const SystemTab: React.FC = () => {
  const [systemStatus, setSystemStatus] = useState<SystemStatus | null>(null);
  const [onboardingState, setOnboardingState] = useState<OnboardingState | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [installing, setInstalling] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [reinstalling, setReinstalling] = useState(false);
  const [installResult, setInstallResult] = useState<InstallResult | null>(null);
  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 [copiedOutput, setCopiedOutput] = useState<string | null>(null);
  const outputEndRef = React.useRef<HTMLDivElement>(null);

  const loadSystemStatus = async () => {
    try {
      const [status, onboarding] = await Promise.all([
        window.settingsAPI.getSystemStatus(),
        window.settingsAPI.getOnboardingState()
      ]);
      setSystemStatus(status);
      setOnboardingState(onboarding);
    } catch (error) {
      console.error('Failed to load system status:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    loadSystemStatus();
  }, []);

  const handleRefresh = async () => {
    setRefreshing(true);
    await loadSystemStatus();
  };

  const handleInstallDocker = async () => {
    if (!systemStatus?.homebrew.installed) {
      setInstallResult({
        success: false,
        message: 'Homebrew is required to install Docker. Please install Homebrew first.'
      });
      return;
    }

    setInstalling(true);
    setInstallResult(null);
    setInstallOutput('');
    setShowInstallOutput(true);

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

    try {
      const result = await window.settingsAPI.installDocker();
      setInstallResult(result);

      if (result.success) {
        setTimeout(() => {
          loadSystemStatus();
        }, 2000);
      }
    } catch (error) {
      console.error('Failed to install Docker:', error);
      setInstallResult({
        success: false,
        message: 'An unexpected error occurred while installing Docker. Please try again.'
      });
    } finally {
      setInstalling(false);
      // Clean up listener
      cleanup();
    }
  };

  const handleUpdateDocker = async () => {
    if (!systemStatus?.homebrew.installed) {
      setInstallResult({
        success: false,
        message: 'Homebrew is required to update Docker. Please install Homebrew first.'
      });
      return;
    }

    setUpdating(true);
    setInstallResult(null);
    setUpdateOutput('');
    setShowUpdateOutput(true);

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

    try {
      const result = await window.settingsAPI.updateDocker();
      setInstallResult(result);

      if (result.success) {
        setTimeout(() => {
          loadSystemStatus();
        }, 2000);
      }
    } catch (error) {
      console.error('Failed to update Docker:', error);
      setInstallResult({
        success: false,
        message: 'An unexpected error occurred while updating Docker. Please try again.'
      });
    } finally {
      setUpdating(false);
      // Clean up listener
      cleanup();
    }
  };

  const handleReinstallDocker = async () => {
    if (!systemStatus?.homebrew.installed) {
      setInstallResult({
        success: false,
        message: 'Homebrew is required to reinstall Docker. Please install Homebrew first.'
      });
      return;
    }

    // Show confirmation dialog
    const confirmed = window.confirm(
      'Docker Desktop will be uninstalled and reinstalled.\n\n' +
      'Important: You will be prompted to authenticate using Touch ID (if available) or your macOS password to authorize the uninstallation.\n\n' +
      'This process may take a few minutes. Continue?'
    );

    if (!confirmed) {
      return;
    }

    setReinstalling(true);
    setInstallResult(null);
    setReinstallOutput('');
    setShowReinstallOutput(true);

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

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

    try {
      const result = await window.settingsAPI.reinstallDocker();
      setInstallResult(result);

      if (result.success) {
        setTimeout(() => {
          loadSystemStatus();
        }, 2000);
      }
    } catch (error) {
      console.error('Failed to reinstall Docker:', error);
      setInstallResult({
        success: false,
        message: 'An unexpected error occurred while reinstalling Docker. Please try again.'
      });
    } finally {
      setReinstalling(false);
      // Clean up listener
      cleanup();
    }
  };

  const handleOpenDocker = async () => {
    try {
      const result = await window.settingsAPI.openDocker();
      if (!result.success) {
        setInstallResult({
          success: false,
          message: result.message || 'Failed to open Docker Desktop'
        });
      }
    } catch (error: any) {
      setInstallResult({
        success: false,
        message: error.message || 'Failed to open Docker Desktop'
      });
    }
  };

  const handleDismissResult = () => {
    setInstallResult(null);
  };

  return (
    <div className="flex-1 p-6 overflow-auto">
      <div className="max-w-4xl">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-base font-semibold text-[#333]">System</h2>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || loading}
            variant="ghost"
            size="sm"
            className="h-9 px-3 text-[#666] hover:text-[#333]"
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>

        {installResult && (
          <div className="mb-6">
            <InstallResultMessage result={installResult} onDismiss={handleDismissResult} />
          </div>
        )}

        {onboardingState && (
          <div className="mb-6">
            <div className="rounded-lg border border-[#e0e0e0] bg-white p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  {onboardingState.completed ? (
                    <>
                      <CheckCircle className="h-5 w-5 text-green-600" />
                      <span className="text-sm text-[#333]">Onboarding completed</span>
                    </>
                  ) : (
                    <>
                      <AlertCircle className="h-5 w-5 text-orange-600" />
                      <span className="text-sm text-[#333]">Onboarding incomplete</span>
                    </>
                  )}
                </div>
                <Button
                  onClick={() => {
                    // Open onboarding window
                    // This would require an IPC call to main process
                    // For now, show a message to user
                    alert('Please use the "Onboard" option from the tray menu to complete setup.');
                  }}
                  variant="ghost"
                  size="sm"
                  className="text-xs"
                >
                  {onboardingState.completed ? 'Review' : 'Complete Setup'}
                </Button>
              </div>
            </div>
          </div>
        )}

        <div className="space-y-4">
          {loading ? (
            <>
              <StatusCardSkeleton title="Docker" />
              <StatusCardSkeleton title="Homebrew" />
            </>
          ) : systemStatus ? (
            <>
              <DockerStatusCard
                status={systemStatus.docker}
                installing={installing}
                updating={updating}
                reinstalling={reinstalling}
                homebrewInstalled={systemStatus.homebrew.installed}
                onInstall={handleInstallDocker}
                onUpdate={handleUpdateDocker}
                onReinstall={handleReinstallDocker}
                onOpenDocker={handleOpenDocker}
              />
              <HomebrewStatusCard status={systemStatus.homebrew} />
            </>
          ) : (
            <div className="text-center py-8">
              <p className="text-[#999] text-sm">Failed to load system status</p>
              <Button onClick={handleRefresh} className="mt-4">
                Retry
              </Button>
            </div>
          )}
        </div>

        {showInstallOutput && (
          <div className="mt-6">
            <div className="rounded-lg border border-[#e0e0e0] bg-white p-4">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-semibold text-[#1a1a1a]">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>
            </div>
          </div>
        )}

        {showUpdateOutput && (
          <div className="mt-6">
            <div className="rounded-lg border border-[#e0e0e0] bg-white p-4">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-semibold text-[#1a1a1a]">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>
            </div>
          </div>
        )}

        {showReinstallOutput && (
          <div className="mt-6">
            <div className="rounded-lg border border-[#e0e0e0] bg-white p-4">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-semibold text-[#1a1a1a]">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>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SystemTab;
