import { useEffect, useState } from 'react';
import { useWorkbenchStore } from '@/features/workspace/WorkspaceStore';
import {
  exportDiagnostics,
  getBundledCliStatus,
  getByokStatus,
  installBundledCli,
  runVigthoriaUpdate,
  setByokConfig,
  vigthoriaLogin,
  vigthoriaLogout,
} from '@/lib/tauri-bridge';
import type { BundledCliStatus, ByokStatus, ToolsTabId } from '@/types/workbench';

export function SettingsModal() {
  const open = useWorkbenchStore((s) => s.settingsOpen);
  const setSettingsOpen = useWorkbenchStore((s) => s.setSettingsOpen);
  const settings = useWorkbenchStore((s) => s.settings);
  const updateSettings = useWorkbenchStore((s) => s.updateSettings);
  const auth = useWorkbenchStore((s) => s.auth);
  const authChecking = useWorkbenchStore((s) => s.authChecking);
  const refreshAuth = useWorkbenchStore((s) => s.refreshAuth);
  const startLogin = useWorkbenchStore((s) => s.startLogin);
  const vigthoriaCliPath = useWorkbenchStore((s) => s.vigthoriaCliPath);
  const appVersion = useWorkbenchStore((s) => s.appVersion);
  const updateInfo = useWorkbenchStore((s) => s.updateInfo);
  const updateChecking = useWorkbenchStore((s) => s.updateChecking);
  const updateBusy = useWorkbenchStore((s) => s.updateBusy);
  const updateMessage = useWorkbenchStore((s) => s.updateMessage);
  const checkAppUpdate = useWorkbenchStore((s) => s.checkAppUpdate);
  const installAppUpdate = useWorkbenchStore((s) => s.installAppUpdate);
  const workspace = useWorkbenchStore((s) => {
    const id = s.activeWorkspaceId;
    return s.workspaces.find((w) => w.id === id) ?? null;
  });
  const saveActiveWorkspaceSettings = useWorkbenchStore((s) => s.saveActiveWorkspaceSettings);

  const [updateLog, setUpdateLog] = useState<string | null>(null);
  const [updating, setUpdating] = useState(false);
  const [loginLog, setLoginLog] = useState<string | null>(null);
  const [loginStarting, setLoginStarting] = useState(false);
  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [signingIn, setSigningIn] = useState(false);
  const [signInError, setSignInError] = useState<string | null>(null);
  const [showAdvancedLogin, setShowAdvancedLogin] = useState(false);
  const [loggingOut, setLoggingOut] = useState(false);
  const [logoutMessage, setLogoutMessage] = useState<string | null>(null);

  const [byokStatus, setByokStatusState] = useState<ByokStatus | null>(null);
  const [byokApiKey, setByokApiKey] = useState('');
  const [byokBaseUrl, setByokBaseUrl] = useState('');
  const [byokModel, setByokModel] = useState('');
  const [byokSaving, setByokSaving] = useState(false);
  const [byokMessage, setByokMessage] = useState<string | null>(null);
  const [bundledCli, setBundledCli] = useState<BundledCliStatus | null>(null);
  const [bundledCliBusy, setBundledCliBusy] = useState(false);
  const [bundledCliMessage, setBundledCliMessage] = useState<string | null>(null);
  const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
  const [diagnosticsMessage, setDiagnosticsMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    void getByokStatus().then((status) => {
      setByokStatusState(status);
      setByokBaseUrl(status.baseUrl);
      setByokModel(status.model);
    });
    void getBundledCliStatus().then(setBundledCli);
  }, [open]);

  const saveByok = async (clearApiKey = false) => {
    setByokSaving(true);
    setByokMessage(null);
    try {
      const status = await setByokConfig(byokApiKey, byokBaseUrl, byokModel, clearApiKey);
      setByokStatusState(status);
      setByokApiKey('');
      setByokMessage(clearApiKey ? 'API key removed.' : 'BYOK settings saved.');
    } catch (e) {
      setByokMessage(`Failed to save: ${e}`);
    } finally {
      setByokSaving(false);
    }
  };

  if (!open) return null;

  return (
    <div className="modal-backdrop" onClick={() => setSettingsOpen(false)}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <header className="modal__header">
          <h2>Settings</h2>
          <button type="button" className="modal__close" onClick={() => setSettingsOpen(false)}>×</button>
        </header>

        <div className="modal__body">
          <section className="settings-section">
            <h3>Application</h3>
            <label className="settings-row">
              <span>Show tools panel (Report · Hyper-Loop · Templates)</span>
              <input
                type="checkbox"
                checked={settings.showReportPanel}
                onChange={(e) => void updateSettings({ showReportPanel: e.target.checked })}
              />
            </label>
            <label className="settings-row">
              <span>Comfort prompt bar (Main Agent)</span>
              <input
                type="checkbox"
                checked={settings.comfortPromptEnabled ?? true}
                onChange={(e) => void updateSettings({ comfortPromptEnabled: e.target.checked })}
              />
            </label>
            <label className="settings-row">
              <span>GOA auto-route (Main Agent comfort prompt)</span>
              <input
                type="checkbox"
                checked={settings.goaAutoRoute ?? true}
                onChange={(e) => void updateSettings({ goaAutoRoute: e.target.checked })}
              />
            </label>
            <label className="settings-row settings-row--stack">
              <span>Default tools tab</span>
              <select
                value={settings.toolsTab ?? 'report'}
                onChange={(e) => void updateSettings({ toolsTab: e.target.value as ToolsTabId })}
              >
                <option value="report">Report</option>
                <option value="hyperloop">Hyper-Loop</option>
                <option value="templates">Templates</option>
                <option value="goa">GOA</option>
              </select>
            </label>
            <label className="settings-row settings-row--stack">
              <span>Vigthoria CLI path (optional)</span>
              <div className="settings-inline">
                <input
                  value={settings.vigthoriaCliPath || ''}
                  placeholder={vigthoriaCliPath ? `Auto-detected: ${vigthoriaCliPath}` : 'Auto-detect from PATH'}
                  onChange={(e) => void updateSettings({ vigthoriaCliPath: e.target.value || undefined })}
                />
                <button type="button" className="settings-btn" onClick={() => void updateSettings({ vigthoriaCliPath: undefined })}>
                  Auto-detect
                </button>
              </div>
              <span className={`settings-status ${vigthoriaCliPath || settings.vigthoriaCliPath ? 'ok' : 'warn'}`}>
                {settings.vigthoriaCliPath
                  ? 'Using custom CLI path.'
                  : vigthoriaCliPath
                    ? 'CLI detected automatically.'
                    : 'CLI not found on PATH.'}
              </span>
              {bundledCli?.available && (
                <div className="settings-actions">
                  <button
                    type="button"
                    className="settings-btn settings-btn--primary"
                    disabled={bundledCliBusy}
                    onClick={() => {
                      setBundledCliBusy(true);
                      setBundledCliMessage(null);
                      void installBundledCli()
                        .then((message) => {
                          setBundledCliMessage(`${message.trim()}\nRestart Workbench to activate the CLI panes.`);
                          return getBundledCliStatus();
                        })
                        .then(setBundledCli)
                        .catch((installError: unknown) => {
                          setBundledCliMessage(
                            installError instanceof Error ? installError.message : String(installError),
                          );
                        })
                        .finally(() => setBundledCliBusy(false));
                    }}
                  >
                    {bundledCliBusy
                      ? 'Installing verified CLI…'
                      : `${vigthoriaCliPath || settings.vigthoriaCliPath ? 'Upgrade / repair' : 'Install'} bundled CLI ${bundledCli.version}`}
                  </button>
                </div>
              )}
              {bundledCliMessage && <pre className="settings-log">{bundledCliMessage}</pre>}
            </label>
          </section>

          <section className="settings-section">
            <h3>Account &amp; updates</h3>
            <div className={`settings-account ${auth.authenticated ? 'is-ok' : 'is-warn'}`}>
              <strong>
                {authChecking
                  ? 'Checking session…'
                  : auth.authenticated
                    ? `Logged in${auth.email ? ` as ${auth.email}` : ''}`
                    : 'Not logged in'}
              </strong>
              <span>
                {authChecking
                  ? 'Verifying your session with the Vigthoria server…'
                  : auth.authenticated
                    ? `${auth.plan ? `Plan: ${auth.plan}. ` : ''}Workbench can use Hyper-Loop and account services.`
                    : auth.message}
              </span>
            </div>
            {auth.authenticated && (
              <div className="settings-actions">
                <button
                  type="button"
                  className="settings-btn settings-btn--danger"
                  disabled={loggingOut}
                  onClick={() => {
                    setLoggingOut(true);
                    setLogoutMessage(null);
                    void vigthoriaLogout(settings.vigthoriaCliPath || vigthoriaCliPath || undefined)
                      .then((msg) => {
                        setLogoutMessage(msg.trim() || 'Logged out.');
                        void refreshAuth(true);
                      })
                      .catch((err: unknown) => setLogoutMessage(err instanceof Error ? err.message : String(err)))
                      .finally(() => setLoggingOut(false));
                  }}
                >
                  {loggingOut ? 'Logging out…' : 'Log out'}
                </button>
              </div>
            )}
            {logoutMessage && <span className="settings-status">{logoutMessage}</span>}
            {!auth.authenticated && (
              <form
                className="settings-login-form"
                onSubmit={(e) => {
                  e.preventDefault();
                  setSigningIn(true);
                  setSignInError(null);
                  void vigthoriaLogin(loginEmail, loginPassword, settings.vigthoriaCliPath || vigthoriaCliPath || undefined)
                    .then(() => {
                      setLoginPassword('');
                      void refreshAuth(true);
                    })
                    .catch((err: unknown) => setSignInError(err instanceof Error ? err.message : String(err)))
                    .finally(() => setSigningIn(false));
                }}
              >
                <label className="settings-row settings-row--stack">
                  <span>Email</span>
                  <input
                    type="email"
                    autoComplete="username"
                    value={loginEmail}
                    onChange={(e) => setLoginEmail(e.target.value)}
                    required
                  />
                </label>
                <label className="settings-row settings-row--stack">
                  <span>Password</span>
                  <input
                    type="password"
                    autoComplete="current-password"
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                    required
                  />
                </label>
                <div className="settings-actions">
                  <button type="submit" className="settings-btn settings-btn--primary" disabled={signingIn}>
                    {signingIn ? 'Signing in…' : 'Sign in'}
                  </button>
                </div>
                {signInError && <span className="settings-status warn">{signInError}</span>}
              </form>
            )}
            <div className="settings-actions">
              <button
                type="button"
                className="settings-btn"
                disabled={authChecking}
                onClick={() => void refreshAuth(true)}
              >
                {authChecking ? 'Checking…' : 'Refresh login status'}
              </button>
              <button
                type="button"
                className="settings-btn"
                disabled={updating}
                onClick={() => {
                  setUpdating(true);
                  setUpdateLog(null);
                  void runVigthoriaUpdate(settings.vigthoriaCliPath || vigthoriaCliPath || undefined)
                    .then((log) => setUpdateLog(log.trim()))
                    .catch((err: unknown) => setUpdateLog(err instanceof Error ? err.message : String(err)))
                    .finally(() => setUpdating(false));
                }}
              >
                {updating ? 'Updating…' : 'Run vigthoria update'}
              </button>
            </div>
            <p className="settings-hint">
              <code>vigthoria update</code> updates the CLI only — no login required. After updating, restart terminals if needed.
            </p>
            {!auth.authenticated && (
              <>
                <button
                  type="button"
                  className="settings-link"
                  onClick={() => setShowAdvancedLogin((v) => !v)}
                >
                  {showAdvancedLogin ? 'Hide advanced sign-in options' : 'Trouble signing in? Advanced options'}
                </button>
                {showAdvancedLogin && (
                  <div className="settings-actions">
                    <button
                      type="button"
                      className="settings-btn"
                      disabled={loginStarting}
                      onClick={() => {
                        setLoginStarting(true);
                        setLoginLog(null);
                        void startLogin()
                          .then(setLoginLog)
                          .catch((err: unknown) => setLoginLog(err instanceof Error ? err.message : String(err)))
                          .finally(() => setLoginStarting(false));
                      }}
                    >
                      {loginStarting ? 'Opening terminal…' : 'Open terminal to sign in'}
                    </button>
                  </div>
                )}
              </>
            )}
            {loginLog && <pre className="settings-log">{loginLog}</pre>}
            {updateLog && <pre className="settings-log">{updateLog}</pre>}
          </section>

          <section className="settings-section">
            <h3>Vigthoria Workbench app</h3>
            <div className={`settings-account ${updateInfo?.updateAvailable ? 'is-warn' : 'is-ok'}`}>
              <strong>
                Workbench {appVersion ? `v${appVersion}` : ''}
              </strong>
              <span>
                {updateChecking
                  ? 'Checking for updates…'
                  : updateInfo?.updateAvailable
                    ? `Update available: v${updateInfo.latestVersion}`
                    : updateInfo
                      ? 'Workbench is up to date.'
                      : 'Not checked yet.'}
              </span>
            </div>
            <div className="settings-actions">
              <button
                type="button"
                className="settings-btn"
                disabled={updateChecking || updateBusy}
                onClick={() => void checkAppUpdate()}
              >
                {updateChecking ? 'Checking…' : 'Check for updates'}
              </button>
              {updateInfo?.updateAvailable && updateInfo.downloadUrl && updateInfo.sha256 && (
                <button
                  type="button"
                  className="settings-btn settings-btn--primary"
                  disabled={updateBusy}
                  onClick={() => void installAppUpdate()}
                >
                  {updateBusy ? 'Installing…' : `Download & install v${updateInfo.latestVersion}`}
                </button>
              )}
            </div>
            {updateInfo?.updateAvailable && (!updateInfo.downloadUrl || !updateInfo.sha256) && (
              <span className="settings-status warn">No installer published for this platform yet.</span>
            )}
            {updateInfo?.updateAvailable && updateInfo.notes && (
              <p className="settings-hint">{updateInfo.notes}</p>
            )}
            {updateInfo?.updateAvailable && updateInfo.downloadUrl && updateInfo.sha256 && (
              <p className="settings-hint">
                Installing will close Workbench and launch the official installer to complete the update.
              </p>
            )}
            {updateMessage && <pre className="settings-log">{updateMessage}</pre>}
          </section>

          <section className="settings-section">
            <h3>Integrated services</h3>
            <label className="settings-row settings-row--stack">
              <span>Hyper-Loop URL</span>
              <input
                value={settings.hyperloopUrl || ''}
                placeholder="https://hyperloop.vigthoria.io"
                onChange={(e) => void updateSettings({ hyperloopUrl: e.target.value })}
              />
            </label>
            <label className="settings-row settings-row--stack">
              <span>Template Service URL</span>
              <input
                value={settings.templateUrl || ''}
                placeholder="https://coder.vigthoria.io/api/template-service"
                onChange={(e) => void updateSettings({ templateUrl: e.target.value })}
              />
            </label>
            <p className="settings-hint">
              Hyper-Loop requires a valid Vigthoria login. Template matching works without auth on the public service.
            </p>
          </section>

          <section className="settings-section">
            <h3>Diagnostics &amp; support</h3>
            <p className="settings-hint">
              Export a structured support file with a correlation ID, app/platform metadata,
              non-secret settings, and the latest diagnostic log. Authentication tokens,
              passwords, and BYOK keys are never included.
            </p>
            <div className="settings-actions">
              <button
                type="button"
                className="settings-btn"
                disabled={diagnosticsBusy}
                onClick={() => {
                  setDiagnosticsBusy(true);
                  setDiagnosticsMessage(null);
                  void exportDiagnostics()
                    .then((path) => setDiagnosticsMessage(`Support file created: ${path}`))
                    .catch((error: unknown) => {
                      setDiagnosticsMessage(error instanceof Error ? error.message : String(error));
                    })
                    .finally(() => setDiagnosticsBusy(false));
                }}
              >
                {diagnosticsBusy ? 'Exporting…' : 'Export support file'}
              </button>
            </div>
            {diagnosticsMessage && <pre className="settings-log">{diagnosticsMessage}</pre>}
          </section>

          <section className="settings-section">
            <h3>API Management (Bring Your Own Key)</h3>
            <p className="settings-hint">
              Configures the "V4 Provider: Bring Your Own Key" option for the V4 Operating Agent workspace preset.
              The key is stored locally in <code>~/.config/vigthoria/config.yaml</code> and is used only by the V4
              Operating Agent's BYOK provider path. It never overwrites or is used by Vigthoria's own Model Router,
              Gateway, V3 Code Agent, or Cloud/Local provider credentials &mdash; those remain entirely server-side
              and are untouched by this setting.
            </p>
            <label className="settings-row settings-row--stack">
              <span>API Key {byokStatus?.hasApiKey ? '(currently set — leave blank to keep it)' : '(not set)'}</span>
              <input
                type="password"
                value={byokApiKey}
                placeholder={byokStatus?.hasApiKey ? 'Leave blank to keep the stored key' : 'sk-...'}
                onChange={(e) => setByokApiKey(e.target.value)}
                autoComplete="off"
              />
            </label>
            <label className="settings-row settings-row--stack">
              <span>Base URL</span>
              <input
                value={byokBaseUrl}
                placeholder="https://api.example.com/v1"
                onChange={(e) => setByokBaseUrl(e.target.value)}
              />
            </label>
            <label className="settings-row settings-row--stack">
              <span>Model</span>
              <input
                value={byokModel}
                placeholder="gpt-4o-mini"
                onChange={(e) => setByokModel(e.target.value)}
              />
            </label>
            <div className="settings-row">
              <button type="button" disabled={byokSaving} onClick={() => void saveByok(false)}>
                {byokSaving ? 'Saving…' : 'Save BYOK settings'}
              </button>
              {byokStatus?.hasApiKey && (
                <button type="button" disabled={byokSaving} onClick={() => void saveByok(true)}>
                  Remove stored key
                </button>
              )}
            </div>
            {byokMessage && <p className="settings-hint">{byokMessage}</p>}
            {byokStatus && <p className="settings-hint">Config file: {byokStatus.configPath}</p>}
          </section>

          {workspace && (
            <section className="settings-section">
              <h3>Active workspace — {workspace.name}</h3>
              <label className="settings-row">
                <span>Debug mode</span>
                <input
                  type="checkbox"
                  checked={workspace.vigthoria.debugMode}
                  onChange={(e) => void saveActiveWorkspaceSettings({ debugMode: e.target.checked })}
                />
              </label>
              <label className="settings-row">
                <span>Auto-save session</span>
                <input
                  type="checkbox"
                  checked={workspace.vigthoria.autoSave}
                  onChange={(e) => void saveActiveWorkspaceSettings({ autoSave: e.target.checked })}
                />
              </label>
              <label className="settings-row">
                <span>Auto-approve tools</span>
                <input
                  type="checkbox"
                  checked={workspace.vigthoria.autoApprove}
                  onChange={(e) => void saveActiveWorkspaceSettings({ autoApprove: e.target.checked })}
                />
              </label>
            </section>
          )}
        </div>
      </div>
    </div>
  );
}
