'use client';

import { FolderTree, LayoutTemplate, Mail, Plus, PanelLeft } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { DraftSummary } from '@/lib/db/draft-repo';
import type { AutoSaveStatus } from '@/hooks/useAutoSave';
import { AutoSaveIndicator } from './AutoSaveIndicator';

/**
 * Reine Icon-Rail-Variante der Sidebar (56px breit).
 *
 * Verantwortlichkeiten:
 *  - Logo zentriert oben.
 *  - "+ Neuer Entwurf" als runder Workspace-Button (öffnet Workspace-Picker im Parent).
 *  - Section-Shortcuts: Klick öffnet Sidebar (`onExpand`) und scrollt zur Section
 *    (`onJumpToSection`).
 *  - Active-Dot oben-rechts auf Section-Icon wenn aktive Draft in dieser Sektion liegt.
 *  - Auto-Save-Indicator im Footer (icon-only).
 *  - Pin-Toggle im Footer (öffnet Sidebar persistent).
 *
 * Komplett kontrolliert — kein eigener State. Hover-Peek-Logik liegt im Parent.
 */

export interface SidebarRailProps {
  drafts: DraftSummary[];
  currentDraftId: string | null;
  templateCount: number;

  autoSaveStatus: AutoSaveStatus;
  autoSaveLastAt: Date | null;
  autoSaveError?: string | null;

  /** Toggle, das die Sidebar pinned-open setzt. */
  onExpand: () => void;
  /** Sidebar pinnen UND zur gegebenen Section scrollen. */
  onJumpToSection: (sectionId: 'projects' | 'templates') => void;
  /** Workspace-Picker öffnen (oder direkt Draft erzeugen wenn nur eine Workspace existiert). */
  onNewDraft: () => void;
}

export function SidebarRail(props: SidebarRailProps) {
  const currentDraft = props.drafts.find((d) => d.id === props.currentDraftId) ?? null;
  const activeBrandId = currentDraft?.workspaceId ?? null;
  const activeBrandColor = currentDraft?.brandPrimaryColor ?? '#0ea5e9';

  return (
    <div className="flex h-full w-full flex-col items-center bg-white dark:bg-zinc-950">
      {/* Logo — purely decorative im Rail, kein Klick-Handler */}
      <div className="pt-3 pb-2">
        <div
          className="flex h-9 w-9 items-center justify-center rounded-md bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900"
          title="MailForge"
        >
          <Mail className="h-4 w-4" />
        </div>
      </div>

      {/* + Neuer Entwurf — runder Workspace-Akzent-Button */}
      <button
        type="button"
        onClick={props.onNewDraft}
        title="Neuer Entwurf"
        className="my-1 flex h-9 w-9 items-center justify-center rounded-full bg-[#ff006a] text-white shadow-sm transition-transform hover:scale-105 hover:bg-[#e60060] active:scale-95"
        aria-label="Neuer Entwurf"
      >
        <Plus className="h-4 w-4" />
      </button>

      <div className="my-2 h-px w-7 bg-zinc-200 dark:bg-zinc-800" />

      {/* Section-Shortcuts: Klick öffnet Sidebar + scrollt zur Section */}
      <nav className="flex flex-1 flex-col items-center gap-1 px-1">
        <RailIcon
          tooltip={`Projekte · ${props.drafts.length}`}
          onClick={() => props.onJumpToSection('projects')}
          dot={activeBrandId ? activeBrandColor : null}
        >
          <FolderTree className="h-[18px] w-[18px]" />
        </RailIcon>
        <RailIcon
          tooltip={`Vorlagen · ${props.templateCount}`}
          onClick={() => props.onJumpToSection('templates')}
          dot={null}
        >
          <LayoutTemplate className="h-[18px] w-[18px]" />
        </RailIcon>
      </nav>

      {/* Footer: Auto-Save-Status (icon-only) + Pin-Toggle */}
      <div className="mt-auto flex flex-col items-center gap-1 pb-3">
        <div className="flex h-9 w-9 items-center justify-center">
          <AutoSaveIndicator
            iconOnly
            status={props.autoSaveStatus}
            lastSavedAt={props.autoSaveLastAt}
            error={props.autoSaveError}
          />
        </div>
        <button
          type="button"
          onClick={props.onExpand}
          title="Sidebar öffnen (⌘\)"
          aria-label="Sidebar öffnen"
          className="flex h-9 w-9 items-center justify-center rounded-md text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
        >
          <PanelLeft className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

/**
 * Internes Icon-Button-Pattern für Rail-Sections.
 *
 * - 36×36 click-target (groß genug für komfortable Maus-Klicks ohne Sidebar zu fluten)
 * - Hover-Background als Primary-Affordance
 * - Active-Dot als zusätzliche additive Information (siehe macOS-Notification-Badges)
 */
function RailIcon({
  tooltip,
  onClick,
  dot,
  children,
}: {
  tooltip: string;
  onClick: () => void;
  dot: string | null;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      title={tooltip}
      aria-label={tooltip}
      className={cn(
        'relative flex h-9 w-9 items-center justify-center rounded-md text-zinc-500 transition-colors',
        'hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-100',
      )}
    >
      {children}
      {dot && (
        <span
          aria-hidden
          className="absolute right-1 top-1 h-2 w-2 rounded-full ring-2 ring-white dark:ring-zinc-950"
          style={{ backgroundColor: dot }}
        />
      )}
    </button>
  );
}
