import React, { useState, useEffect } from 'react';
import { CheckCircle2, AlertCircle, RefreshCw, Play, Square, ChevronDown, ChevronUp, Terminal } from 'lucide-react';
import { 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 { Badge } from '../../components/ui/badge';
import frpcIcon from '../../assets/frpc-icon.png';

interface FrpcConfigStatus {
  serviceFileExists: boolean;
  configFileExists: boolean;
  isRunning: boolean;
  configured: boolean;
  canvasUrl: string | null;
  folderName: string | null;
}

export const FrpcConfigStep: React.FC = () => {
  const { refreshStepStatus, refreshTrigger, currentStepIndex, steps, setStepWorking } = useSetupWizard();
  const prevStepIndexRef = React.useRef<number | null>(null);
  const [status, setStatus] = useState<FrpcConfigStatus>({
    serviceFileExists: false,
    configFileExists: false,
    isRunning: false,
    configured: false,
    canvasUrl: null,
    folderName: null
  });
  const [starting, setStarting] = useState(false);
  const [stopping, setStopping] = 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 checkStatus = async (forceRefresh = false) => {
    try {
      const frpcConfigStatus = await window.setupWizardAPI.getFrpcConfigStatus();
      setStatus(frpcConfigStatus);

      // Refresh validation status
      await refreshStepStatus('frpc-config');
    } catch (error) {
      console.error('Failed to check FRPC config status:', error);
    }
  };

  useEffect(() => {
    const loadInitialStatus = async () => {
      await checkStatus();
      setRefreshing(false);
    };
    loadInitialStatus();
  }, []);

  // Listen to refresh trigger from context
  useEffect(() => {
    if (refreshTrigger > 0) {
      handleRefresh();
    }
  }, [refreshTrigger]);

  // Refresh when navigating back to this step
  useEffect(() => {
    const currentStep = steps[currentStepIndex];
    if (
      currentStep?.id === 'frpc-config' &&
      prevStepIndexRef.current !== null &&
      prevStepIndexRef.current !== currentStepIndex
    ) {
      handleRefresh();
    }
    prevStepIndexRef.current = currentStepIndex;
  }, [currentStepIndex, steps]);

  const handleRefresh = async () => {
    setRefreshing(true);
    setResult(null);
    await checkStatus(true);
    setRefreshing(false);
  };

  const handleStart = async () => {
    setStepWorking('frpc-config', true);
    setStarting(true);
    setResult(null);

    try {
      const startResult = await window.setupWizardAPI.startFrpcService();
      setResult(startResult);

      if (startResult.success) {
        await checkStatus(true);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to start FRPC service'
      });
    } finally {
      setStarting(false);
      setStepWorking('frpc-config', false);
    }
  };

  const handleStop = async () => {
    setStepWorking('frpc-config', true);
    setStopping(true);
    setResult(null);

    try {
      const stopResult = await window.setupWizardAPI.stopFrpcService();
      setResult(stopResult);

      if (stopResult.success) {
        await checkStatus(true);
      }
    } catch (error: any) {
      setResult({
        success: false,
        message: error.message || 'Failed to stop FRPC service'
      });
    } finally {
      setStopping(false);
      setStepWorking('frpc-config', 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'
      });
    }
  };

  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 FRPC as a system service
          </p>
          <Button
            onClick={handleRefresh}
            disabled={refreshing || starting || stopping}
            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 FRPC Config?
                </p>
                <p>
                  This step configures FRPC (Fast Reverse Proxy Client) to run as a macOS LaunchAgent service,
                  enabling automatic startup and persistent background operation.
                </p>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Why is it needed?
                </p>
                <p>
                  Running FRPC as a service ensures it starts automatically when you log in and continues
                  running in the background, maintaining your reverse proxy connection without manual intervention.
                </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>Creates LaunchAgent plist file in ~/Library/LaunchAgents/</li>
                  <li>Creates FRPC configuration file at ~/frp/frpc.toml</li>
                  <li>Loads and starts the FRPC service</li>
                  <li>Verifies the service is running</li>
                  <li>Provides controls to start and stop the service</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 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={frpcIcon} alt="FRPC" className="w-full h-full object-cover" />
            </div>
            <div>
              <h3 className="text-[15px] font-semibold text-foreground">FRPC Service</h3>
              <div className="mt-1">
                {status.isRunning ? (
                  <Badge variant="success" className="text-xs">
                    <CheckCircle2 className="h-3.5 w-3.5 mr-1" />
                    Running
                  </Badge>
                ) : (
                  <Badge variant="secondary" className="text-xs">
                    <AlertCircle className="h-3.5 w-3.5 mr-1" />
                    Stopped
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="space-y-4">
          {/* Service Status */}
          <Alert variant={status.isRunning ? "success" : status.serviceFileExists ? "warning" : "default"}>
            {status.isRunning ? <CheckCircle2 className="h-5 w-5" /> : <AlertCircle className="h-5 w-5" />}
            <AlertDescription>
              <p className="font-medium mb-1">
                {status.isRunning
                  ? 'FRPC service is running'
                  : status.serviceFileExists && status.configFileExists
                  ? 'FRPC service is configured but not running'
                  : 'FRPC service needs to be configured'}
              </p>
              <div className="text-xs mt-2 space-y-1">
                <div>Service file: {status.serviceFileExists ? '✓ Exists' : '✗ Missing'}</div>
                <div>Config file: {status.configFileExists ? '✓ Exists' : '✗ Missing'}</div>
                <div>Service status: {status.isRunning ? '✓ Running' : '✗ Stopped'}</div>
              </div>
            </AlertDescription>
          </Alert>

          {/* Canvas URL */}
          {status.canvasUrl && (
            <div className="space-y-2">
              <h4 className="text-sm font-medium text-foreground">
                Canvas Site
              </h4>
              {status.configured ? (
                <Alert variant="success">
                  <CheckCircle2 className="h-5 w-5" />
                  <AlertDescription>
                    <p className="font-medium mb-1">FRPC tunnel is active</p>
                    <p className="text-xs">
                      URL: <a href={status.canvasUrl} target="_blank" rel="noopener noreferrer" className="text-green-700 dark:text-green-400 underline">{status.canvasUrl}</a>
                    </p>
                  </AlertDescription>
                </Alert>
              ) : (
                <Alert variant="warning">
                  <AlertCircle className="h-5 w-5" />
                  <AlertDescription>
                    <p className="font-medium mb-1">FRPC tunnel not active</p>
                    <p className="text-xs">
                      Expected URL: <code className="bg-yellow-100 dark:bg-yellow-900/30 px-1 rounded">{status.canvasUrl}</code>
                    </p>
                  </AlertDescription>
                </Alert>
              )}
            </div>
          )}

          {/* Control Buttons */}
          <div className="flex gap-2">
            <Button
              onClick={handleStart}
              disabled={starting || stopping || status.isRunning}
              className="flex-1"
              variant="default"
            >
              {starting ? (
                <>
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  Starting...
                </>
              ) : (
                <>
                  <Play className="h-4 w-4 mr-2" />
                  Start Service
                </>
              )}
            </Button>

            <Button
              onClick={handleStop}
              disabled={starting || stopping || !status.isRunning}
              className="flex-1"
              variant="outline"
            >
              {stopping ? (
                <>
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  Stopping...
                </>
              ) : (
                <>
                  <Square className="h-4 w-4 mr-2" />
                  Stop Service
                </>
              )}
            </Button>
          </div>

          <div className="pt-3 border-t border-border">
            <p className="text-xs mb-2 text-muted-foreground">
              <strong>Note:</strong> This step configures FRPC to run as a LaunchAgent service.
            </p>
            <ul className="text-xs space-y-1 list-disc list-inside text-muted-foreground">
              <li>Service will start automatically on login</li>
              <li>Configuration stored at <code className="bg-muted px-1 rounded">~/frp/frpc.toml</code></li>
              <li>Service logs available at <code className="bg-muted px-1 rounded">~/frp/frpc.log</code></li>
            </ul>
          </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">
                  Service won't start
                </p>
                <p>
                  If the service fails to start:
                </p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Ensure FRPC is installed (FRPC Install step)</li>
                  <li>Check FRPC is available at <code className="bg-secondary px-1 rounded">/opt/homebrew/bin/frpc</code></li>
                  <li>Review service logs at <code className="bg-secondary px-1 rounded">~/frp/frpc.log</code></li>
                  <li>Check error logs at <code className="bg-secondary px-1 rounded">~/frp/frpc_error.log</code></li>
                </ul>
              </div>

              <div className="space-y-2">
                <p className="font-medium text-foreground">
                  Manual service management
                </p>
                <p>
                  To manually manage the service:
                </p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>Check status: <code className="bg-secondary px-1 rounded">launchctl list | grep frpc</code></li>
                  <li>View logs: <code className="bg-secondary px-1 rounded">cat ~/frp/frpc.log</code></li>
                  <li>Restart: Stop then Start the service</li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};
