import {
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { invoke } from '@tauri-apps/api/core';

import {
  AlertTriangle,
  CheckCircle2,
  Cpu,
  FileUp,
  Network,
  PlugZap,
  RefreshCw,
  Rocket,
  Search,
  ShieldAlert,
  Terminal,
  UploadCloud,
  Wifi
} from 'lucide-react';

import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';

import { addActivityLog } from '@/services/activityLogService';
import { vpnApi } from '@/services/vpnApi';

type ProvisioningMode =
  | 'full'
  | 'provision_only';

type WorkflowStep =
  | 'DETECT_ROUTER'
  | 'UPLOAD_FIRMWARE'
  | 'FLASH_FIRMWARE'
  | 'WAIT_REBOOT'
  | 'RECONNECT_ROUTER'
  | 'UPLOAD_PROVISIONING'
  | 'RUN_PROVISIONING'
  | 'REGISTER_PEER';

type StepStatus =
  | 'pending'
  | 'active'
  | 'done'
  | 'blocked';

type DetectionStatus =
  | 'idle'
  | 'checking'
  | 'reachable'
  | 'ssh_ok'
  | 'auth_required'
  | 'stale_host_key'
  | 'failed'
  | 'flashing'
  | 'waiting_reboot'
  | 'reconnecting';

type RouterEnvForm = {
  routerId: string;
  hostname: string;
  wgIp: string;
  rootPassword: string;
};

const routerPresets = [
  {
    ip: '192.168.1.1',
    label: 'Factory/default',
    password: '',
  },
  {
    ip: '198.51.100.1',
    label: 'Provisioned LAN',
    password: 'litoralr',
  },
];

const FLASH_SECONDS = 300;
const PROVISION_SECONDS = 90;

const stopPhrase = 'STOP PROVISIONING';

const workflowSteps: Array<{
  id: WorkflowStep;
  title: string;
  description: string;
  icon: typeof Search;
}> = [
    {
      id: 'DETECT_ROUTER',
      title: 'Detect Router',
      description: 'Ping and inspect router over SSH.',
      icon: Search,
    },
    {
      id: 'UPLOAD_FIRMWARE',
      title: 'Upload Firmware',
      description: 'Copy firmware image to /tmp.',
      icon: UploadCloud,
    },
    {
      id: 'FLASH_FIRMWARE',
      title: 'Flash Firmware',
      description: 'Run sysupgrade -n /tmp/firmware.bin.',
      icon: Cpu,
    },
    {
      id: 'WAIT_REBOOT',
      title: 'Wait for Reboot',
      description: 'Block actions while router restarts.',
      icon: RefreshCw,
    },
    {
      id: 'RECONNECT_ROUTER',
      title: 'Reconnect Router',
      description: 'Reconnect Ethernet and wait for SSH.',
      icon: PlugZap,
    },
    {
      id: 'UPLOAD_PROVISIONING',
      title: 'Upload Bundle',
      description: 'Copy router.env and provision.sh.',
      icon: FileUp,
    },
    {
      id: 'RUN_PROVISIONING',
      title: 'Run Provisioning',
      description: 'Execute router-side setup script.',
      icon: Terminal,
    },
    {
      id: 'REGISTER_PEER',
      title: 'Register VPS Peer',
      description: 'Apply WireGuard peer on VPS.',
      icon: Network,
    }
  ];

const scrollClass =
  '[scrollbar-width:thin] [scrollbar-color:rgba(59,130,246,0.45)_transparent] [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-blue-500/30 hover:[&::-webkit-scrollbar-thumb]:bg-blue-500/50';

function statusTone(status: DetectionStatus) {
  if (
    status === 'reachable' ||
    status === 'ssh_ok'
  ) {
    return 'green';
  }

  if (
    status === 'auth_required' ||
    status === 'stale_host_key' ||
    status === 'flashing' ||
    status === 'waiting_reboot' ||
    status === 'reconnecting'
  ) {
    return 'purple';
  }

  if (status === 'failed') {
    return 'red';
  }

  return 'blue';
}

function statusLabel(status: DetectionStatus) {
  return status.replace(/_/g, ' ');
}

function formatSeconds(totalSeconds: number) {
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  return `${minutes}:${String(seconds).padStart(2, '0')}`;
}

function defaultRouterEnv(): RouterEnvForm {
  return {
    routerId: '',
    hostname: '',
    wgIp: '',
    rootPassword: 'litoralr',
  };
}

function buildRouterEnv(form: RouterEnvForm) {
  return [
    `ROUTER_ID=${form.routerId}`,
    `HOSTNAME=${form.hostname}`,
    '',
    'LAN_IP=198.51.100.1',
    'LAN_NETMASK=255.255.255.0',
    '',
    `WG_IP=${form.wgIp}`,
    'WG_CIDR=32',
    'WG_SERVER_HOST=146.59.230.190',
    'WG_SERVER_PORT=4999',
    'WG_SERVER_PUBLIC_KEY=eSe9hH/X1tcAqGo09hDHvOXmy6o6NPk5sPwCzMXE7kc=',
    '',
    'CONTROLLER_IP=198.51.100.10',
    'PLC_IP=198.51.100.50',
    '',
    `ROOT_PASSWORD=${form.rootPassword.trim() || 'litoralr'}`,
    '',
  ].join('\n');
}

export function ProvisioningWizard() {
  const [provisioningMode, setProvisioningMode] =
    useState<ProvisioningMode>('full');

  const [selectedIp, setSelectedIp] =
    useState(routerPresets[0].ip);

  const [customIp, setCustomIp] = useState('');
  const [routerPassword, setRouterPassword] =
    useState(routerPresets[0].password);
  const [customPassword, setCustomPassword] =
    useState('');

  const [status, setStatus] =
    useState<DetectionStatus>('idle');

  const [activeStep, setActiveStep] =
    useState<WorkflowStep>('DETECT_ROUTER');

  const [completedSteps, setCompletedSteps] =
    useState<WorkflowStep[]>([]);

  const [routerInfo, setRouterInfo] =
    useState('');

  const [log, setLog] = useState<string[]>([]);

  const [confirmFlashOpen, setConfirmFlashOpen] =
    useState(false);

  const [flashOverlayOpen, setFlashOverlayOpen] =
    useState(false);

  const [flashSecondsRemaining, setFlashSecondsRemaining] =
    useState(FLASH_SECONDS);

  const [isReconnecting, setIsReconnecting] =
    useState(false);

  const [envModalOpen, setEnvModalOpen] =
    useState(false);

  const [routerEnv, setRouterEnv] =
    useState<RouterEnvForm>(defaultRouterEnv());

  const [stopConfirmOpen, setStopConfirmOpen] =
    useState(false);

  const [stopConfirmText, setStopConfirmText] =
    useState('');

  const flashCompletionHandledRef =
    useRef(false);

  const [provisionOverlayOpen, setProvisionOverlayOpen] =
    useState(false);

  const [provisionSecondsRemaining, setProvisionSecondsRemaining] =
    useState(PROVISION_SECONDS);


  const [isActionRunning, setIsActionRunning] =
    useState(false);

  const [setupCompleteOpen, setSetupCompleteOpen] =
    useState(false);

  const effectivePassword =
    customIp.trim() &&
      selectedIp === customIp.trim()
      ? customPassword
      : routerPassword;

  const provisioningStarted =
    activeStep !== 'DETECT_ROUTER' ||
    completedSteps.length > 0 ||
    status === 'flashing' ||
    status === 'waiting_reboot' ||
    status === 'reconnecting';

  const controlsLocked =
    provisioningStarted ||
    isReconnecting ||
    isActionRunning;

  const canContinue =
    status === 'ssh_ok' ||
    completedSteps.includes('UPLOAD_FIRMWARE') ||
    activeStep === 'UPLOAD_PROVISIONING' ||
    activeStep === 'RUN_PROVISIONING' ||
    activeStep === 'REGISTER_PEER';

  const visibleWorkflowSteps = useMemo(() => {
    if (provisioningMode === 'full') {
      return workflowSteps;
    }

    return workflowSteps.filter(
      (step) =>
        ![
          'UPLOAD_FIRMWARE',
          'FLASH_FIRMWARE',
          'WAIT_REBOOT',
          'RECONNECT_ROUTER',
        ].includes(step.id),
    );
  }, [provisioningMode]);

  const flashProgress =
    ((FLASH_SECONDS - flashSecondsRemaining) /
      FLASH_SECONDS) *
    100;

  const workflowState = useMemo(() => {
    return visibleWorkflowSteps.map((step) => {
      let stepStatus: StepStatus = 'pending';

      if (completedSteps.includes(step.id)) {
        stepStatus = 'done';
      } else if (step.id === activeStep) {
        stepStatus = 'active';
      }

      if (
        !canContinue &&
        step.id !== 'DETECT_ROUTER'
      ) {
        stepStatus = 'blocked';
      }

      return {
        ...step,
        status: stepStatus,
      };
    });
  }, [
    activeStep,
    completedSteps,
    canContinue,
    visibleWorkflowSteps,
  ]);

  function addLog(
    message: string,
    level:
      | 'info'
      | 'success'
      | 'warning'
      | 'error' = 'info',
  ) {
    setLog((currentLog) => [
      `${new Date().toLocaleTimeString()}  ${message}`,
      ...currentLog,
    ]);

    addActivityLog({
      level,
      source: 'desktop',
      action: activeStep,
      message,
      routerIp: selectedIp,
    });
  }

  function resetProvisioning(shouldLog = true) {
    setProvisioningMode('full');
    setSelectedIp(routerPresets[0].ip);
    setRouterPassword(routerPresets[0].password);
    setCustomIp('');
    setCustomPassword('');

    setActiveStep('DETECT_ROUTER');
    setCompletedSteps([]);
    setStatus('idle');
    setRouterInfo('');
    setIsReconnecting(false);
    setIsActionRunning(false);

    setFlashOverlayOpen(false);
    setConfirmFlashOpen(false);
    setProvisionOverlayOpen(false);
    setEnvModalOpen(false);
    setStopConfirmOpen(false);
    setStopConfirmText('');
    setSetupCompleteOpen(false);

    setRouterEnv(defaultRouterEnv());

    flashCompletionHandledRef.current = false;

    if (shouldLog) {
      addLog(
        'Provisioning flow was reset.',
        'warning',
      );
    }
  }

  function finishProvisioning() {
    resetProvisioning(false);

    setLog((currentLog) => [
      `${new Date().toLocaleTimeString()}  Router setup completed successfully. Ready for next router.`,
      ...currentLog,
    ]);
  }

  useEffect(() => {
    if (!flashOverlayOpen) {
      return;
    }

    const intervalId = window.setInterval(() => {
      setFlashSecondsRemaining((current) => {
        if (current <= 1) {
          window.clearInterval(intervalId);

          if (!flashCompletionHandledRef.current) {
            flashCompletionHandledRef.current = true;

            setFlashOverlayOpen(false);
            setStatus('waiting_reboot');

            setCompletedSteps((currentSteps) => [
              ...new Set([
                ...currentSteps,
                'FLASH_FIRMWARE' as WorkflowStep,
                'WAIT_REBOOT' as WorkflowStep,
              ]),
            ]);

            setSelectedIp(routerPresets[0].ip);
            setRouterPassword(routerPresets[0].password);
            setCustomIp('');
            setCustomPassword('');

            setActiveStep('RECONNECT_ROUTER');

            addLog(
              'Flash wait window completed. Reconnect or replug Ethernet if needed, then continue with reconnect checks.',
              'success',
            );
          }

          return 0;
        }

        return current - 1;
      });
    }, 1000);

    return () => {
      window.clearInterval(intervalId);
    };
  }, [flashOverlayOpen]);

  useEffect(() => {
    if (!provisionOverlayOpen) {
      return;
    }

    const intervalId = window.setInterval(() => {
      setProvisionSecondsRemaining((current) => {
        if (current <= 1) {
          window.clearInterval(intervalId);

          setProvisionOverlayOpen(false);

          setSelectedIp(routerPresets[1].ip);
          setRouterPassword(routerPresets[1].password);
          setCustomIp('');
          setCustomPassword('');

          setActiveStep('REGISTER_PEER');

          addLog(
            'Provisioning wait completed. Replug Ethernet now, wait a few seconds, then continue to verify WireGuard and register peer.',
            'warning',
          );

          return 0;
        }

        return current - 1;
      });
    }, 1000);

    return () => {
      window.clearInterval(intervalId);
    };
  }, [provisionOverlayOpen]);

  async function detectRouter() {
    if (controlsLocked) {
      addLog(
        'Router detection is locked while provisioning is active.',
        'warning',
      );
      return;
    }

    if (!selectedIp.trim()) {
      addLog(
        'Router detection blocked: no IP selected',
        'warning',
      );
      return;
    }

    setActiveStep('DETECT_ROUTER');
    setStatus('checking');
    setRouterInfo('');

    addLog(
      `Starting safe router detection at ${selectedIp}`,
    );

    try {
      await invoke<boolean>('ping_host', {
        ip: selectedIp,
      });

      addLog(
        `Router responded at ${selectedIp}`,
        'success',
      );

      try {
        const info = await invoke<string>(
          'probe_router_ssh',
          {
            ip: selectedIp,
          },
        );

        setRouterInfo(info);
        setStatus('ssh_ok');
        setCompletedSteps(['DETECT_ROUTER']);

        setActiveStep(
          provisioningMode === 'full'
            ? 'UPLOAD_FIRMWARE'
            : 'UPLOAD_PROVISIONING',
        );

        addLog(
          `SSH key authentication succeeded at ${selectedIp}`,
          'success',
        );

        return;
      } catch (sshError) {
        const sshMessage = String(sshError);

        if (
          sshMessage.includes(
            'STALE_HOST_KEY',
          )
        ) {
          setStatus('stale_host_key');

          addLog(
            `Stale SSH host key detected for ${selectedIp}`,
            'warning',
          );

          return;
        }

        if (
          sshMessage.includes(
            'AUTH_REQUIRED',
          )
        ) {
          addLog(
            'Router requires password authentication. Attempting automatic inspection...',
            'warning',
          );

          try {
            const passwordInfo =
              await invoke<string>(
                'inspect_router_with_password',
                {
                  ip: selectedIp,
                  password: effectivePassword,
                },
              );

            setRouterInfo(passwordInfo);
            setStatus('ssh_ok');
            setCompletedSteps([
              'DETECT_ROUTER',
            ]);

            setActiveStep(
              provisioningMode === 'full'
                ? 'UPLOAD_FIRMWARE'
                : 'UPLOAD_PROVISIONING',
            );

            addLog(
              `Password SSH inspection succeeded at ${selectedIp}`,
              'success',
            );

            return;
          } catch (passwordError) {
            setStatus('auth_required');

            addLog(
              `Password authentication failed: ${String(
                passwordError,
              )}`,
              'error',
            );

            return;
          }
        }

        throw sshError;
      }
    } catch (error) {
      const message = String(error);

      setStatus('failed');

      addLog(
        `Router detection failed: ${message}`,
        'error',
      );
    }
  }

  async function fixKnownHost() {
    if (controlsLocked) {
      addLog(
        'Known host cleanup is locked while provisioning is active.',
        'warning',
      );
      return;
    }

    if (!selectedIp.trim()) {
      addLog(
        'Cannot remove known_hosts entry: no IP selected',
        'warning',
      );
      return;
    }

    try {
      addLog(
        `Removing known_hosts entry for ${selectedIp}`,
      );

      const result = await invoke<string>(
        'remove_known_host',
        {
          ip: selectedIp,
        },
      );

      addLog(result, 'success');
      setStatus('idle');
      setCompletedSteps([]);
      setActiveStep('DETECT_ROUTER');
    } catch (error) {
      addLog(String(error), 'error');
    }
  }

  async function continueProvisioning() {
    if (isActionRunning || isReconnecting) {
      return;
    }

    setIsActionRunning(true);

    try {
      await continueProvisioningInner();
    } finally {
      setIsActionRunning(false);
    }
  }

  async function continueProvisioningInner() {
    if (activeStep === 'UPLOAD_FIRMWARE') {
      try {
        addLog(
          `Uploading firmware to ${selectedIp}:/tmp/firmware.bin`,
        );

        const result = await invoke<string>(
          'upload_firmware_to_router',
          {
            ip: selectedIp,
            password: effectivePassword,
          },
        );

        addLog(result, 'success');

        setCompletedSteps((currentSteps) => [
          ...new Set([
            ...currentSteps,
            'UPLOAD_FIRMWARE' as WorkflowStep,
          ]),
        ]);

        setActiveStep('FLASH_FIRMWARE');

        return;
      } catch (error) {
        addLog(
          `Firmware upload failed: ${String(error)}`,
          'error',
        );

        return;
      }
    }

    if (activeStep === 'FLASH_FIRMWARE') {
      setConfirmFlashOpen(true);
      return;
    }

    if (activeStep === 'RECONNECT_ROUTER') {
      if (isReconnecting) {
        return;
      }

      setIsReconnecting(true);
      setStatus('reconnecting');

      addLog(
        `Checking router SSH after flash at ${selectedIp}`,
        'warning',
      );

      for (let attempt = 1; attempt <= 30; attempt += 1) {
        try {
          addLog(`Reconnect attempt ${attempt}/30`);

          const info = await invoke<string>(
            'check_router_after_flash',
            {
              ip: selectedIp,
              password: effectivePassword,
            },
          );

          setRouterInfo(info);

          addLog(
            `Router SSH reconnected after flash at ${selectedIp}`,
            'success',
          );

          setCompletedSteps((currentSteps) => [
            ...new Set([
              ...currentSteps,
              'RECONNECT_ROUTER' as WorkflowStep,
            ]),
          ]);

          setStatus('ssh_ok');
          setActiveStep('UPLOAD_PROVISIONING');
          setIsReconnecting(false);

          return;
        } catch (error) {
          addLog(
            `Reconnect attempt ${attempt}/30 failed: ${String(error)}`,
            'warning',
          );

          await new Promise((resolve) =>
            window.setTimeout(resolve, 5000),
          );
        }
      }

      setStatus('failed');
      setIsReconnecting(false);

      addLog(
        'Router reconnect failed after 30 attempts. Replug Ethernet and retry.',
        'error',
      );

      return;
    }

    if (activeStep === 'UPLOAD_PROVISIONING') {
      await prepareRouterEnv();
      return;
    }

    if (activeStep === 'RUN_PROVISIONING') {
      setProvisionSecondsRemaining(PROVISION_SECONDS);
      setProvisionOverlayOpen(true);

      try {
        addLog(
          `Running provisioning script on ${selectedIp}`,
          'warning',
        );

        const result = await invoke<string>(
          'run_provisioning',
          {
            ip: selectedIp,
            password: effectivePassword,
          },
        );

        addLog(result, 'success');
      } catch (error) {
        const message = String(error);
        const lowered = message.toLowerCase();

        const expectedProvisionDisconnect =
          lowered.includes('connection reset') ||
          lowered.includes('client_loop') ||
          lowered.includes('failed to connect to ubus') ||
          lowered.includes('disconnect') ||
          lowered.includes('broken pipe') ||
          lowered.includes('restart') ||
          lowered.includes('radio0');

        if (expectedProvisionDisconnect) {
          addLog(
            'Provisioning script reached network/service restart and SSH disconnected as expected.',
            'warning',
          );

          addLog(message, 'info');
        } else {
          setProvisionOverlayOpen(false);

          addLog(
            `Provisioning script failed: ${message}`,
            'error',
          );

          return;
        }
      }

      setCompletedSteps((currentSteps) => [
        ...new Set([
          ...currentSteps,
          'RUN_PROVISIONING' as WorkflowStep,
        ]),
      ]);

      setActiveStep('REGISTER_PEER');

      return;
    }

    if (activeStep === 'REGISTER_PEER') {
      try {
        addLog(
          `Capturing router WireGuard public key from ${routerPresets[1].ip}`,
          'warning',
        );

        const publicKey = await invoke<string>(
          'capture_wireguard_public_key',
          {
            ip: routerPresets[1].ip,
            password: routerEnv.rootPassword.trim() || routerPresets[1].password,
          },
        );

        addLog(
          `Captured router public key ${publicKey.slice(0, 12)}...`,
          'success',
        );

        await vpnApi.registerPeer({
          vpnIp: routerEnv.wgIp,
          publicKey,
        });

        addLog(
          `Registered VPS peer ${routerEnv.wgIp}`,
          'success',
        );

        setCompletedSteps((currentSteps) => [
          ...new Set([
            ...currentSteps,
            'REGISTER_PEER' as WorkflowStep,
          ]),
        ]);

        setStatus('ssh_ok');
        setSetupCompleteOpen(true);

        return;
      } catch (error) {
        addLog(
          `Peer registration failed: ${String(error)}`,
          'error',
        );

        return;
      }
    }

    addLog(
      `Step ${activeStep} is not wired yet.`,
      'warning',
    );
  }

  async function uploadProvisioningBundle() {
    if (
      !routerEnv.routerId.trim() ||
      !routerEnv.hostname.trim() ||
      !routerEnv.wgIp.trim()
    ) {
      addLog(
        'router.env is missing router ID, hostname, or WireGuard IP.',
        'error',
      );
      return;
    }

    try {
      const envContent = buildRouterEnv(routerEnv);

      addLog(
        `Uploading router.env and provision.sh to ${selectedIp}`,
        'warning',
      );

      const result = await invoke<string>(
        'upload_provisioning_bundle',
        {
          ip: selectedIp,
          password: effectivePassword,
          envContent,
        },
      );

      addLog(result, 'success');

      setEnvModalOpen(false);

      setCompletedSteps((currentSteps) => [
        ...new Set([
          ...currentSteps,
          'UPLOAD_PROVISIONING' as WorkflowStep,
        ]),
      ]);

      setActiveStep('RUN_PROVISIONING');
    } catch (error) {
      addLog(
        `Provisioning bundle upload failed: ${String(error)}`,
        'error',
      );
    }
  }

  async function confirmAndFlashRouter() {
    setConfirmFlashOpen(false);
    setStatus('flashing');
    setActiveStep('FLASH_FIRMWARE');

    flashCompletionHandledRef.current = false;

    addLog(
      'Starting firmware flash with sysupgrade -n /tmp/firmware.bin',
      'warning',
    );

    try {
      await invoke<string>(
        'flash_router_sysupgrade',
        {
          ip: selectedIp,
          password: effectivePassword,
        },
      );

      addLog(
        'Flash command submitted. SSH session may disconnect; entering protected wait window.',
        'success',
      );
    } catch (error) {
      const message = String(error);
      const loweredMessage = message.toLowerCase();

      if (
        loweredMessage.includes('broken pipe') ||
        loweredMessage.includes('connection reset') ||
        loweredMessage.includes('channel') ||
        loweredMessage.includes('disconnect') ||
        loweredMessage.includes('commencing upgrade') ||
        loweredMessage.includes('closing all shell sessions') ||
        loweredMessage.includes('connection failed') ||
        loweredMessage.includes('sysupgrade')
      ) {
        addLog(
          'Router accepted sysupgrade and disconnected as expected during flash.',
          'warning',
        );
      } else {
        setStatus('failed');

        addLog(
          `Flash command failed before reboot: ${message}`,
          'error',
        );

        return;
      }
    }

    setFlashSecondsRemaining(FLASH_SECONDS);
    setFlashOverlayOpen(true);
  }

  async function prepareRouterEnv() {
    try {
      addLog(
        'Requesting next available WireGuard IP from backend...',
      );

      const response = await vpnApi.availableIp();
      const vpnIp = response.vpnIp;

      const vpnParts = vpnIp.split('.');
      const routerId =
        vpnParts[vpnParts.length - 1] || '';

      setRouterEnv((current) => ({
        ...current,
        routerId,
        hostname: `Litoral_Regas_${routerId}`,
        wgIp: vpnIp,
      }));

      addLog(
        `Reserved next available WireGuard IP candidate: ${vpnIp}`,
        'success',
      );

      setEnvModalOpen(true);
    } catch (error) {
      addLog(
        `Failed to get available WireGuard IP: ${String(error)}`,
        'error',
      );
    }
  }

  return (
    <div className="flex h-full flex-col overflow-hidden">
      <div className="mb-5 flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight text-white">
            Provisioning
          </h1>

          <p className="mt-1 text-slate-400">
            Guided router provisioning from
            detection to VPS peer registration.
          </p>
        </div>

        <div className="flex items-center gap-3">
          {provisioningStarted && (
            <Button
              type="button"
              variant="danger"
              onClick={() => setStopConfirmOpen(true)}
              disabled={
                status === 'flashing' ||
                isReconnecting ||
                isActionRunning
              }
            >
              Stop Provisioning
            </Button>
          )}

          <Badge tone={statusTone(status)}>
            {statusLabel(status)}
          </Badge>
        </div>
      </div>

      <div className="grid min-h-0 flex-1 grid-cols-12 gap-5 overflow-hidden">
        <Card className="col-span-5 flex min-h-0 flex-col overflow-hidden">
          <div
            className={`min-h-0 flex-1 overflow-y-auto pr-1 ${scrollClass}`}
          >
            <div className="mb-5 flex items-center gap-4">
              <div className="rounded-2xl bg-blue-500/10 p-3 text-blue-300">
                <Search size={24} />
              </div>

              <div>
                <h2 className="text-xl font-semibold text-white">
                  Router Connection
                </h2>

                <p className="text-sm text-slate-400">
                  Select target and validate SSH
                  before provisioning.
                </p>
              </div>
            </div>

            <div className="mb-4 grid grid-cols-2 gap-3">
              <button
                type="button"
                disabled={controlsLocked}
                onClick={() =>
                  setProvisioningMode('full')
                }
                className={`rounded-2xl border p-4 text-left transition disabled:cursor-not-allowed disabled:opacity-60 ${provisioningMode === 'full'
                  ? 'border-blue-500/40 bg-blue-500/10'
                  : 'border-white/10 bg-white/[0.02]'
                  }`}
              >
                <p className="font-semibold text-white">
                  Full Provisioning
                </p>
                <p className="mt-1 text-xs text-slate-500">
                  Flash firmware, reconnect, then provision.
                </p>
              </button>

              <button
                type="button"
                disabled={controlsLocked}
                onClick={() =>
                  setProvisioningMode('provision_only')
                }
                className={`rounded-2xl border p-4 text-left transition disabled:cursor-not-allowed disabled:opacity-60 ${provisioningMode === 'provision_only'
                  ? 'border-blue-500/40 bg-blue-500/10'
                  : 'border-white/10 bg-white/[0.02]'
                  }`}
              >
                <p className="font-semibold text-white">
                  Provision Only
                </p>
                <p className="mt-1 text-xs text-slate-500">
                  Router is already flashed and stable.
                </p>
              </button>
            </div>

            <div className="grid grid-cols-2 gap-3">
              {routerPresets.map((preset) => {
                const active =
                  selectedIp === preset.ip &&
                  customIp.trim() === '';

                return (
                  <button
                    key={preset.ip}
                    type="button"
                    disabled={controlsLocked}
                    onClick={() => {
                      setSelectedIp(preset.ip);
                      setRouterPassword(preset.password);
                      setCustomIp('');
                    }}
                    className={`rounded-2xl border p-4 text-left transition disabled:cursor-not-allowed disabled:opacity-60 ${active
                      ? 'border-blue-500/40 bg-blue-500/10'
                      : 'border-white/10 bg-white/[0.02] hover:border-blue-500/20 hover:bg-white/[0.04]'
                      }`}
                  >
                    <Network
                      size={18}
                      className={
                        active
                          ? 'text-blue-300'
                          : 'text-slate-500'
                      }
                    />

                    <p className="mt-3 font-mono text-sm font-semibold text-white">
                      {preset.ip}
                    </p>

                    <p className="mt-1 text-xs text-slate-500">
                      {preset.label}
                    </p>

                    <p className="mt-3 text-xs text-slate-500">
                      Password:{' '}
                      <span className="font-mono text-slate-300">
                        {preset.password || 'empty'}
                      </span>
                    </p>
                  </button>
                );
              })}

              <div
                className={`col-span-2 rounded-2xl border p-4 transition ${customIp.trim()
                  ? 'border-blue-500/40 bg-blue-500/10'
                  : 'border-white/10 bg-white/[0.02]'
                  }`}
              >
                <div className="mb-3 flex items-center gap-3">
                  <Network
                    size={18}
                    className={
                      customIp.trim()
                        ? 'text-blue-300'
                        : 'text-slate-500'
                    }
                  />

                  <div>
                    <p className="text-sm font-semibold text-white">
                      Custom Router Access
                    </p>

                    <p className="text-xs text-slate-500">
                      Use this for non-standard router IPs
                      or passwords.
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-slate-500">
                      Router IP
                    </label>

                    <input
                      disabled={controlsLocked}
                      value={customIp}
                      onChange={(event) => {
                        const value =
                          event.target.value;

                        setCustomIp(value);
                        setSelectedIp(value.trim());
                      }}
                      onFocus={() => {
                        setSelectedIp(customIp.trim());
                      }}
                      placeholder="Example: 192.168.8.1"
                      className="w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2 font-mono text-sm text-white outline-none transition focus:border-blue-500/40 disabled:cursor-not-allowed disabled:opacity-60"
                    />
                  </div>

                  <div>
                    <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-slate-500">
                      SSH Password
                    </label>

                    <input
                      disabled={controlsLocked}
                      type="password"
                      value={customPassword}
                      onChange={(event) =>
                        setCustomPassword(
                          event.target.value,
                        )
                      }
                      onFocus={() => {
                        if (customIp.trim()) {
                          setSelectedIp(
                            customIp.trim(),
                          );
                        }
                      }}
                      placeholder="Leave empty if no password"
                      className="w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2 font-mono text-sm text-white outline-none transition focus:border-blue-500/40 disabled:cursor-not-allowed disabled:opacity-60"
                    />
                  </div>
                </div>
              </div>
            </div>

            <div className="mt-4 rounded-2xl border border-white/10 bg-slate-950/70 p-4">
              <div className="flex items-start gap-4">
                <div className="rounded-2xl bg-green-500/10 p-3 text-green-300">
                  <Wifi size={22} />
                </div>

                <div className="flex-1">
                  <p className="font-semibold text-white">
                    Detection Target
                  </p>

                  <p className="mt-1 font-mono text-sm text-slate-400">
                    root@{selectedIp || '—'}
                  </p>
                </div>

                <Badge tone={statusTone(status)}>
                  {statusLabel(status)}
                </Badge>
              </div>
            </div>

            <div className="mt-4 flex flex-wrap gap-3">
              <Button
                type="button"
                onClick={detectRouter}
                disabled={
                  controlsLocked ||
                  status === 'checking' ||
                  !selectedIp.trim()
                }
              >
                <Search size={16} />
                Detect Router
              </Button>

              <Button
                type="button"
                variant="secondary"
                onClick={fixKnownHost}
                disabled={
                  controlsLocked ||
                  !selectedIp.trim()
                }
              >
                <ShieldAlert size={16} />
                Fix Known Host
              </Button>
            </div>
          </div>
        </Card>

        <div className="col-span-4 flex min-h-0 flex-col gap-5">
          <Card className="flex min-h-0 flex-1 flex-col overflow-hidden">
            <div className="mb-4 flex items-center gap-3">
              <div className="rounded-2xl bg-blue-500/10 p-3 text-blue-300">
                <Rocket size={22} />
              </div>

              <div>
                <h2 className="text-lg font-semibold text-white">
                  Provisioning Flow
                </h2>

                <p className="text-sm text-slate-400">
                  Full router onboarding sequence.
                </p>
              </div>
            </div>

            <div
              className={`min-h-0 flex-1 space-y-3 overflow-y-auto pr-1 ${scrollClass}`}
            >
              {workflowState.map((step) => (
                <WorkflowStepCard
                  key={step.id}
                  title={step.title}
                  description={step.description}
                  icon={step.icon}
                  status={step.status}
                />
              ))}
            </div>

            <div className="mt-4">
              <Button
                type="button"
                onClick={continueProvisioning}
                disabled={
                  !canContinue ||
                  status === 'flashing' ||
                  isReconnecting ||
                  isActionRunning
                }
              >
                <Rocket size={16} />
                {isActionRunning
                  ? 'Working...'
                  : isReconnecting
                    ? 'Reconnecting...'
                    : 'Continue Provisioning'}
              </Button>
            </div>
          </Card>
        </div>

        <div className="col-span-3 flex min-h-0 flex-col gap-5">
          <Card className="flex min-h-0 flex-1 flex-col overflow-hidden">
            <div className="mb-4 flex items-center gap-3">
              <div className="rounded-2xl bg-blue-500/10 p-3 text-blue-300">
                <Terminal size={22} />
              </div>

              <div>
                <h2 className="text-lg font-semibold text-white">
                  Router Info
                </h2>

                <p className="text-sm text-slate-400">
                  ubus system board output.
                </p>
              </div>
            </div>

            <pre
              className={`min-h-0 flex-1 overflow-auto whitespace-pre-wrap rounded-2xl border border-white/10 bg-slate-950 p-4 font-mono text-xs text-slate-300 ${scrollClass}`}
            >
              {routerInfo || 'No router information captured yet.'}
            </pre>
          </Card>
        </div>
      </div>

      <Card className="mt-4 flex h-52 flex-col overflow-hidden">
        <h3 className="mb-2 text-sm font-semibold text-white">
          Technician Log
        </h3>

        <pre
          className={`min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-xl border border-white/10 bg-slate-950/70 p-3 font-mono text-sm text-slate-300 ${scrollClass}`}
        >
          {log.join('\n') || 'No provisioning activity yet.'}
        </pre>
      </Card>

      {confirmFlashOpen && (
        <ConfirmFlashModal
          selectedIp={selectedIp}
          onCancel={() => setConfirmFlashOpen(false)}
          onConfirm={confirmAndFlashRouter}
        />
      )}

      {flashOverlayOpen && (
        <FlashOverlay
          flashSecondsRemaining={flashSecondsRemaining}
          flashProgress={flashProgress}
        />
      )}

      {provisionOverlayOpen && (
        <ProvisionOverlay
          provisionSecondsRemaining={provisionSecondsRemaining}
          provisionProgress={
            ((PROVISION_SECONDS - provisionSecondsRemaining) /
              PROVISION_SECONDS) *
            100
          }
        />
      )}

      {envModalOpen && (
        <RouterEnvModal
          routerEnv={routerEnv}
          setRouterEnv={setRouterEnv}
          onCancel={() => setEnvModalOpen(false)}
          onUpload={uploadProvisioningBundle}
        />
      )}

      {stopConfirmOpen && (
        <StopProvisioningModal
          value={stopConfirmText}
          onChange={setStopConfirmText}
          onCancel={() => {
            setStopConfirmOpen(false);
            setStopConfirmText('');
          }}
          onConfirm={() => resetProvisioning(true)}
          canConfirm={stopConfirmText === stopPhrase}
        />
      )}

      {setupCompleteOpen && (
        <SetupCompleteModal
          routerId={routerEnv.routerId}
          hostname={routerEnv.hostname}
          wgIp={routerEnv.wgIp}
          onClose={finishProvisioning}
        />
      )}
    </div>
  );
}

function RouterEnvModal({
  routerEnv,
  setRouterEnv,
  onCancel,
  onUpload,
}: {
  routerEnv: RouterEnvForm;
  setRouterEnv: React.Dispatch<
    React.SetStateAction<RouterEnvForm>
  >;
  onCancel: () => void;
  onUpload: () => void;
}) {
  function updateField(
    field: keyof RouterEnvForm,
    value: string,
  ) {
    setRouterEnv((current) => ({
      ...current,
      [field]: value,
    }));
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm">
      <div className="w-full max-w-3xl rounded-3xl border border-blue-500/30 bg-slate-950 p-6 shadow-2xl shadow-blue-500/10">
        <div className="mb-5 flex items-center gap-4">
          <div className="rounded-2xl bg-blue-500/10 p-3 text-blue-300">
            <FileUp size={26} />
          </div>

          <div>
            <h2 className="text-2xl font-bold text-white">
              Router Environment
            </h2>

            <p className="text-sm text-slate-400">
              Values used to generate router.env before upload.
            </p>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <EnvInput
            label="Router ID"
            value={routerEnv.routerId}
            onChange={(value) => updateField('routerId', value)}
            placeholder="203"
          />

          <EnvInput
            label="Hostname"
            value={routerEnv.hostname}
            onChange={(value) => updateField('hostname', value)}
            placeholder="Litoral_Regas_203"
          />

          <EnvInput
            label="WireGuard IP"
            value={routerEnv.wgIp}
            onChange={(value) => updateField('wgIp', value)}
            placeholder="198.19.1.203"
          />

          <EnvInput
            label="Root Password"
            value={routerEnv.rootPassword}
            onChange={(value) => updateField('rootPassword', value)}
            placeholder="litoralr"
            type="password"
          />
        </div>

        <div className="mt-5 rounded-2xl border border-white/10 bg-white/[0.02] p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Static router.env values
          </p>

          <div className="mt-3 grid grid-cols-2 gap-3 font-mono text-xs text-slate-300">
            <p>LAN_IP=198.51.100.1</p>
            <p>LAN_NETMASK=255.255.255.0</p>
            <p>WG_CIDR=32</p>
            <p>WG_SERVER_HOST=146.59.230.190</p>
            <p>WG_SERVER_PORT=4999</p>
            <p>CONTROLLER_IP=198.51.100.10</p>
            <p>PLC_IP=198.51.100.50</p>
            <p className="truncate">
              WG_SERVER_PUBLIC_KEY=eSe9hH/X1tcAqGo09hDHvOXmy6o6NPk5sPwCzMXE7kc=
            </p>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <Button type="button" variant="secondary" onClick={onCancel}>
            Cancel
          </Button>

          <Button type="button" onClick={onUpload}>
            <FileUp size={16} />
            Upload Bundle
          </Button>
        </div>
      </div>
    </div>
  );
}

function EnvInput({
  label,
  value,
  onChange,
  placeholder,
  type = 'text',
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  type?: string;
}) {
  return (
    <div>
      <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-slate-500">
        {label}
      </label>

      <input
        type={type}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        placeholder={placeholder}
        className="w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2 font-mono text-sm text-white outline-none transition focus:border-blue-500/40"
      />
    </div>
  );
}

function ConfirmFlashModal({
  selectedIp,
  onCancel,
  onConfirm,
}: {
  selectedIp: string;
  onCancel: () => void;
  onConfirm: () => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm">
      <div className="w-full max-w-xl rounded-3xl border border-red-500/30 bg-slate-950 p-6 shadow-2xl shadow-red-500/10">
        <div className="flex gap-4">
          <div className="rounded-2xl bg-red-500/10 p-3 text-red-300">
            <AlertTriangle size={28} />
          </div>

          <div>
            <h2 className="text-2xl font-bold text-white">
              Confirm Firmware Flash
            </h2>

            <p className="mt-3 text-sm leading-6 text-slate-300">
              This will run{' '}
              <span className="font-mono text-red-200">
                sysupgrade -n /tmp/firmware.bin
              </span>{' '}
              on router{' '}
              <span className="font-mono text-red-200">
                {selectedIp}
              </span>
              . The SSH session will drop and the router may be unreachable for several minutes.
            </p>

            <div className="mt-5 rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-100">
              Do not unplug router power. Do not close this application.
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <Button type="button" variant="secondary" onClick={onCancel}>
                Cancel
              </Button>

              <Button type="button" onClick={onConfirm} className="bg-red-500 hover:bg-red-400">
                <Cpu size={16} />
                Flash Router
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FlashOverlay({
  flashSecondsRemaining,
  flashProgress,
}: {
  flashSecondsRemaining: number;
  flashProgress: number;
}) {
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/85 backdrop-blur-md">
      <div className="w-full max-w-2xl rounded-3xl border border-purple-500/30 bg-slate-950 p-8 shadow-2xl shadow-purple-500/20">
        <div className="flex items-start gap-5">
          <div className="rounded-3xl bg-purple-500/10 p-4 text-purple-300">
            <RefreshCw size={34} className="animate-spin" />
          </div>

          <div className="flex-1">
            <h2 className="text-3xl font-bold text-white">
              Flashing router firmware
            </h2>

            <p className="mt-3 leading-7 text-slate-300">
              The router is applying firmware and rebooting. The SSH session will be unavailable during this window.
            </p>

            <div className="mt-6 rounded-2xl border border-white/10 bg-white/[0.03] p-5">
              <div className="mb-3 flex items-center justify-between text-sm">
                <span className="text-slate-400">
                  Protected wait window
                </span>

                <span className="font-mono text-purple-200">
                  {formatSeconds(flashSecondsRemaining)}
                </span>
              </div>

              <div className="h-3 overflow-hidden rounded-full bg-slate-800">
                <div
                  className="h-full rounded-full bg-purple-400 transition-all duration-1000"
                  style={{ width: `${flashProgress}%` }}
                />
              </div>
            </div>

            <div className="mt-6 rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm leading-6 text-red-100">
              Do not unplug power. Do not close this app. Wait for this screen to finish before touching the Ethernet cable.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ProvisionOverlay({
  provisionSecondsRemaining,
  provisionProgress,
}: {
  provisionSecondsRemaining: number;
  provisionProgress: number;
}) {
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/85 backdrop-blur-md">
      <div className="w-full max-w-2xl rounded-3xl border border-blue-500/30 bg-slate-950 p-8 shadow-2xl shadow-blue-500/20">
        <div className="flex items-start gap-5">
          <div className="rounded-3xl bg-blue-500/10 p-4 text-blue-300">
            <RefreshCw size={34} className="animate-spin" />
          </div>

          <div className="flex-1">
            <h2 className="text-3xl font-bold text-white">
              Applying router provisioning
            </h2>

            <p className="mt-3 leading-7 text-slate-300">
              The router is changing LAN, firewall, WireGuard, LuCI,
              and root password settings. SSH or Ethernet may drop during this step.
            </p>

            <div className="mt-6 rounded-2xl border border-white/10 bg-white/[0.03] p-5">
              <div className="mb-3 flex items-center justify-between text-sm">
                <span className="text-slate-400">
                  Protected provisioning window
                </span>

                <span className="font-mono text-blue-200">
                  {formatSeconds(provisionSecondsRemaining)}
                </span>
              </div>

              <div className="h-3 overflow-hidden rounded-full bg-slate-800">
                <div
                  className="h-full rounded-full bg-blue-400 transition-all duration-1000"
                  style={{ width: `${provisionProgress}%` }}
                />
              </div>
            </div>

            <div className="mt-6 rounded-2xl border border-yellow-500/20 bg-yellow-500/10 p-4 text-sm leading-6 text-yellow-100">
              Do not unplug power. When this timer finishes, unplug and replug Ethernet,
              then continue to verify WireGuard and register the VPS peer.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function StopProvisioningModal({
  value,
  onChange,
  onCancel,
  onConfirm,
  canConfirm,
}: {
  value: string;
  onChange: (value: string) => void;
  onCancel: () => void;
  onConfirm: () => void;
  canConfirm: boolean;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm">
      <div className="w-full max-w-xl rounded-3xl border border-red-500/30 bg-slate-950 p-6 shadow-2xl shadow-red-500/10">
        <div className="flex gap-4">
          <div className="rounded-2xl bg-red-500/10 p-3 text-red-300">
            <AlertTriangle size={28} />
          </div>

          <div className="flex-1">
            <h2 className="text-2xl font-bold text-white">
              Stop Provisioning?
            </h2>

            <p className="mt-3 text-sm leading-6 text-slate-300">
              Stopping in the middle of provisioning can leave the router in a partial or broken state. Only continue if you know the current router state is safe.
            </p>

            <p className="mt-5 text-sm text-slate-400">
              Type{' '}
              <span className="font-mono text-red-200">
                {stopPhrase}
              </span>{' '}
              to confirm.
            </p>

            <input
              value={value}
              onChange={(event) => onChange(event.target.value)}
              className="mt-3 w-full rounded-xl border border-red-500/20 bg-slate-950 px-3 py-2 font-mono text-sm text-white outline-none focus:border-red-400/50"
            />

            <div className="mt-6 flex justify-end gap-3">
              <Button type="button" variant="secondary" onClick={onCancel}>
                Cancel
              </Button>

              <Button
                type="button"
                variant="danger"
                disabled={!canConfirm}
                onClick={onConfirm}
              >
                Stop Provisioning
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function WorkflowStepCard({
  title,
  description,
  icon: Icon,
  status,
}: {
  title: string;
  description: string;
  icon: typeof Search;
  status: StepStatus;
}) {
  const active = status === 'active';
  const done = status === 'done';
  const blocked = status === 'blocked';

  return (
    <div
      className={`rounded-2xl border p-3 transition ${done
        ? 'border-green-500/30 bg-green-500/10'
        : active
          ? 'border-blue-500/40 bg-blue-500/10'
          : blocked
            ? 'border-white/5 bg-white/[0.015] opacity-60'
            : 'border-white/10 bg-white/[0.02]'
        }`}
    >
      <div className="flex gap-3">
        <div
          className={`rounded-xl p-2 ${done
            ? 'bg-green-500/10 text-green-300'
            : active
              ? 'bg-blue-500/10 text-blue-300'
              : 'bg-slate-900 text-slate-500'
            }`}
        >
          <Icon size={16} />
        </div>

        <div>
          <p className="text-sm font-semibold text-white">
            {title}
          </p>

          <p className="mt-1 text-xs leading-5 text-slate-500">
            {description}
          </p>
        </div>
      </div>
    </div>
  );
}

function SetupCompleteModal({
  routerId,
  hostname,
  wgIp,
  onClose,
}: {
  routerId: string;
  hostname: string;
  wgIp: string;
  onClose: () => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm">
      <div className="w-full max-w-xl rounded-3xl border border-green-500/30 bg-slate-950 p-6 shadow-2xl shadow-green-500/10">
        <div className="flex gap-4">
          <div className="rounded-2xl bg-green-500/10 p-3 text-green-300">
            <CheckCircle2 size={30} />
          </div>

          <div className="flex-1">
            <h2 className="text-2xl font-bold text-white">
              Router setup completed
            </h2>

            <p className="mt-3 text-sm leading-6 text-slate-300">
              Router provisioning finished successfully and the VPS WireGuard peer was registered.
            </p>

            <div className="mt-5 rounded-2xl border border-white/10 bg-white/[0.03] p-4 font-mono text-sm text-slate-300">
              <p>ROUTER_ID={routerId}</p>
              <p>HOSTNAME={hostname}</p>
              <p>WG_IP={wgIp}</p>
            </div>

            <div className="mt-6 flex justify-end">
              <Button type="button" onClick={onClose}>
                Done
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}