import React, { useState, useEffect } from 'react';
import { useShadeContext } from '../ShadeProvider.js';
import { IdentityCard } from './IdentityCard.js';
import { SessionList } from './SessionList.js';
import { PrekeyStock } from './PrekeyStock.js';
import { RecentActivity } from './RecentActivity.js';
import { ServerStatus } from './ServerStatus.js';
import { FingerprintCompare } from './FingerprintCompare.js';

/**
 * WidgetCatalog — meta-widget that lets the user pick which Shade widgets
 * to display in their dashboard. Selection is persisted to localStorage
 * (or via onLayoutChange callback).
 */

export type WidgetKey = 'identity' | 'sessions' | 'prekeys' | 'activity' | 'server' | 'fingerprint';

const ALL_WIDGETS: Record<WidgetKey, { label: string; component: React.ComponentType }> = {
  identity: { label: 'Identity', component: IdentityCard },
  sessions: { label: 'Sessions', component: SessionList },
  prekeys: { label: 'Prekey stock', component: PrekeyStock },
  activity: { label: 'Recent activity', component: RecentActivity },
  server: { label: 'Server status', component: ServerStatus },
  fingerprint: { label: 'Verify fingerprint', component: FingerprintCompare },
};

export interface WidgetCatalogProps {
  /** Which widgets are available for selection. Default: all. */
  available?: WidgetKey[];
  /** Initial layout if nothing in localStorage. Default: identity, sessions, activity. */
  defaultLayout?: WidgetKey[];
  /** Optional callback when user changes the layout (for persistence) */
  onLayoutChange?: (layout: WidgetKey[]) => void;
  /** localStorage key to persist layout. Default: "shade-widget-layout" */
  storageKey?: string;
}

export function WidgetCatalog({
  available = Object.keys(ALL_WIDGETS) as WidgetKey[],
  defaultLayout = ['identity', 'sessions', 'activity'],
  onLayoutChange,
  storageKey = 'shade-widget-layout',
}: WidgetCatalogProps): React.ReactElement {
  const { theme } = useShadeContext();
  const [layout, setLayout] = useState<WidgetKey[]>(() => {
    if (typeof window === 'undefined') return defaultLayout;
    try {
      const stored = window.localStorage.getItem(storageKey);
      if (stored) {
        const parsed = JSON.parse(stored) as WidgetKey[];
        if (Array.isArray(parsed)) return parsed.filter((k) => available.includes(k));
      }
    } catch {}
    return defaultLayout;
  });
  const [editing, setEditing] = useState(false);

  useEffect(() => {
    try {
      window.localStorage.setItem(storageKey, JSON.stringify(layout));
    } catch {}
    onLayoutChange?.(layout);
  }, [layout, onLayoutChange, storageKey]);

  function toggle(key: WidgetKey): void {
    setLayout((current) => {
      if (current.includes(key)) {
        return current.filter((k) => k !== key);
      }
      return [...current, key];
    });
  }

  return (
    <div className="shade-widget-catalog" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '4px 0',
        }}
      >
        <span style={{ fontSize: 12, color: theme.textMuted }}>
          {layout.length} widget{layout.length !== 1 ? 's' : ''} active
        </span>
        <button
          onClick={() => setEditing(!editing)}
          style={{
            background: 'transparent',
            border: `1px solid ${theme.border}`,
            color: theme.text,
            borderRadius: theme.radius,
            padding: '4px 12px',
            fontSize: 11,
            fontFamily: theme.font,
            cursor: 'pointer',
          }}
        >
          {editing ? 'Done' : 'Customize'}
        </button>
      </div>

      {editing && (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
            gap: 8,
            padding: 12,
            background: theme.bgElevated,
            border: `1px solid ${theme.border}`,
            borderRadius: theme.radius,
          }}
        >
          {available.map((key) => {
            const isActive = layout.includes(key);
            return (
              <label
                key={key}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 6,
                  padding: '6px 8px',
                  background: isActive ? theme.accentMuted : theme.bg,
                  border: `1px solid ${isActive ? theme.accent : theme.border}`,
                  borderRadius: 4,
                  cursor: 'pointer',
                  fontSize: 12,
                  color: isActive ? theme.accent : theme.text,
                  fontFamily: theme.font,
                }}
              >
                <input
                  type="checkbox"
                  checked={isActive}
                  onChange={() => toggle(key)}
                  style={{ accentColor: theme.accent }}
                />
                {ALL_WIDGETS[key].label}
              </label>
            );
          })}
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {layout.map((key) => {
          const W = ALL_WIDGETS[key].component;
          return <W key={key} />;
        })}
      </div>
    </div>
  );
}
