import { AlertTriangle, LogOut, Trash2, X } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';

import { cn } from '@/lib/utils';

import { AccessTokensTab } from './settings/AccessTokensTab';
import { AccountTab } from './settings/AccountTab';
import { AppearanceTab } from './settings/AppearanceTab';
import { DevicesTab } from './settings/DevicesTab';
import { GpgKeysTab } from './settings/GpgKeysTab';
import { NotificationsTab } from './settings/NotificationsTab';
import { OAuthAccountsTab } from './settings/OAuthAccountsTab';
import { ProfileTab } from './settings/ProfileTab';
import { SecurityLogsTab } from './settings/SecurityLogsTab';
import { SessionsTab } from './settings/SessionsTab';
import { SshKeysTab } from './settings/SshKeysTab';

type Tab =
  | 'account'
  | 'profile'
  | 'appearance'
  | 'notifications'
  | 'sessions'
  | 'ssh-keys'
  | 'gpg-keys'
  | 'devices'
  | 'access-tokens'
  | 'oauth'
  | 'security-logs';

const SIDEBAR_GROUPS: { label: string; items: { id: Tab; label: string }[] }[] = [
  {
    label: 'Public profile',
    items: [
      { id: 'account', label: 'Account' },
      { id: 'profile', label: 'Profile' },
    ],
  },
  {
    label: 'Preferences',
    items: [
      { id: 'appearance', label: 'Appearance' },
      { id: 'notifications', label: 'Notifications' },
    ],
  },
  {
    label: 'Security',
    items: [
      { id: 'sessions', label: 'Sessions' },
      { id: 'ssh-keys', label: 'SSH Keys' },
      { id: 'gpg-keys', label: 'GPG Keys' },
      { id: 'devices', label: 'Devices' },
      { id: 'access-tokens', label: 'Access tokens' },
      { id: 'oauth', label: 'Linked accounts' },
      { id: 'security-logs', label: 'Security log' },
    ],
  },
];

const ALL_TABS = SIDEBAR_GROUPS.flatMap((g) => g.items);

interface SettingsModalProps {
  open: boolean;
  onClose: () => void;
}

export function SettingsModal({ open, onClose }: SettingsModalProps) {
  const [tab, setTab] = useState<Tab>('account');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const modalRef = useRef<HTMLDivElement>(null);

  // Escape to close
  useEffect(() => {
    if (!open) return;
    function handleEscape(e: KeyboardEvent) {
      if (e.key === 'Escape') {
        if (deleteConfirmOpen) {
          setDeleteConfirmOpen(false);
        } else {
          onClose();
        }
      }
    }
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [open, onClose, deleteConfirmOpen]);

  // Reset state when opening
  useEffect(() => {
    if (open) {
      setTab('account');
      setDeleteConfirmOpen(false);
    }
  }, [open]);

  // Keyboard navigation for sidebar tabs
  const handleSidebarKeyDown = useCallback((e: React.KeyboardEvent, currentId: Tab) => {
    const idx = ALL_TABS.findIndex((t) => t.id === currentId);
    let nextIdx: number | null = null;

    if (e.key === 'ArrowDown') {
      e.preventDefault();
      nextIdx = idx + 1 < ALL_TABS.length ? idx + 1 : 0;
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      nextIdx = idx - 1 >= 0 ? idx - 1 : ALL_TABS.length - 1;
    }

    if (nextIdx !== null) {
      setTab(ALL_TABS[nextIdx].id);
      document.getElementById(`sidebar-tab-${ALL_TABS[nextIdx].id}`)?.focus();
    }
  }, []);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center">
      {/* Backdrop */}
      <button
        type="button"
        aria-label="Close settings"
        className="absolute inset-0 bg-background/50 backdrop-blur-[2px] border-0 p-0 cursor-default"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        ref={modalRef}
        className="relative flex h-[88vh] max-h-[780px] w-full max-w-[900px] overflow-hidden rounded-xl bg-card shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-border/60"
      >
        {/* Close button */}
        <button
          type="button"
          onClick={onClose}
          className="absolute right-3 top-3 z-10 flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
        >
          <X className="size-4" />
        </button>

        {/* Sidebar */}
        <aside className="flex w-[224px] shrink-0 flex-col border-r border-border bg-muted">
          <div className="flex h-[52px] shrink-0 items-center px-4">
            <span className="text-sm font-semibold text-foreground">Settings</span>
          </div>

          <nav className="flex-1 overflow-y-auto px-2 py-1">
            {SIDEBAR_GROUPS.map((group, gi) => (
              <div key={group.label} className={gi > 0 ? 'mt-4' : ''}>
                <h3 className="mb-1 px-2 text-[11px] font-semibold uppercase tracking-[0.03em] text-muted-foreground">
                  {group.label}
                </h3>
                {group.items.map((item) => (
                  <button
                    key={item.id}
                    id={`sidebar-tab-${item.id}`}
                    type="button"
                    role="tab"
                    aria-selected={tab === item.id}
                    onClick={() => setTab(item.id)}
                    onKeyDown={(e) => handleSidebarKeyDown(e, item.id)}
                    className={cn(
                      'relative w-full rounded-md px-2 py-[6px] text-left text-[14px] leading-[20px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/40',
                      tab === item.id
                        ? 'bg-card text-foreground shadow-[0_1px_3px_rgba(0,0,0,0.06)] ring-1 ring-border/80'
                        : 'text-foreground hover:bg-secondary',
                    )}
                  >
                    {item.label}
                  </button>
                ))}
              </div>
            ))}
          </nav>

          {/* Footer actions */}
          <div className="shrink-0 border-t border-border px-4 py-3 space-y-1">
            <button
              type="button"
              className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-[13px] text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
            >
              <LogOut className="size-4 shrink-0" />
              Log out
            </button>
            <button
              type="button"
              onClick={() => setDeleteConfirmOpen(true)}
              className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-[13px] text-destructive transition-colors hover:bg-destructive/10"
            >
              <Trash2 className="size-4 shrink-0" />
              Delete account
            </button>
          </div>
        </aside>

        {/* Content */}
        <main className="flex min-w-0 flex-1 flex-col overflow-y-auto bg-card" role="tabpanel">
          {tab === 'account' && <AccountTab />}
          {tab === 'profile' && <ProfileTab />}
          {tab === 'appearance' && <AppearanceTab />}
          {tab === 'notifications' && <NotificationsTab />}
          {tab === 'sessions' && <SessionsTab />}
          {tab === 'ssh-keys' && <SshKeysTab />}
          {tab === 'gpg-keys' && <GpgKeysTab />}
          {tab === 'devices' && <DevicesTab />}
          {tab === 'access-tokens' && <AccessTokensTab />}
          {tab === 'oauth' && <OAuthAccountsTab />}
          {tab === 'security-logs' && <SecurityLogsTab />}
        </main>
      </div>

      {/* Delete account confirmation dialog */}
      {deleteConfirmOpen && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-background/30 backdrop-blur-[1px]">
          <div className="w-full max-w-[400px] rounded-xl bg-card p-6 shadow-[0_12px_32px_rgba(0,0,0,0.12)] ring-1 ring-border/80">
            <div className="flex items-center gap-3 mb-4">
              <div className="flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
                <AlertTriangle className="size-5 text-destructive" />
              </div>
              <div>
                <h2 className="text-[16px] font-semibold text-foreground">Delete account</h2>
                <p className="text-[13px] text-muted-foreground">
                  This action is permanent and cannot be undone.
                </p>
              </div>
            </div>
            <p className="mb-6 text-[14px] text-foreground leading-relaxed">
              All of your data, including repositories, settings, and session history will be
              permanently removed. You will lose access to all workspaces.
            </p>
            <div className="flex items-center justify-end gap-2">
              <button
                type="button"
                onClick={() => setDeleteConfirmOpen(false)}
                className="rounded-md px-4 py-[6px] text-[13px] font-medium text-foreground transition-colors hover:bg-muted"
              >
                Cancel
              </button>
              <button
                type="button"
                className="rounded-md bg-destructive px-4 py-[6px] text-[13px] font-medium text-destructive-foreground transition-colors hover:bg-destructive/80"
              >
                Delete my account
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
