'use client';

import React from 'react';
import { App, Button, Segmented } from 'antd';
import { useAppTheme } from '../../context/ThemeContext';
import { ACCENT_PRESETS, normalizeHexColor, type AccentPreset, type FontChoice, type FontScale, type RadiusStyle, type SidebarStyle, type SurfaceTone, type ThemeChoice } from '../../theme/tokens';
import { Icon } from '../ui/Icon';

const THEME_CARDS: Array<{
  value: ThemeChoice;
  label: string;
  prevClass: string;
}> = [
  { value: 'light', label: 'Light', prevClass: '' },
  { value: 'dark', label: 'Dark', prevClass: 'dark' },
  { value: 'system', label: 'Match system', prevClass: 'sys' },
];

const ACCENT_ORDER: Array<Exclude<AccentPreset, 'custom'>> = ['red', 'teal', 'blue', 'indigo', 'orange', 'graphite'];

export function WorkspaceAppearanceView() {
  const { message } = App.useApp();
  const { mode, prefs, updatePrefs, resetPrefs } = useAppTheme();

  const applyUpdate = (patch: Parameters<typeof updatePrefs>[0], notice?: string) => {
    updatePrefs(patch);
    if (notice) message.success(notice);
  };

  const activeHex = prefs.accent === 'custom' ? normalizeHexColor(prefs.customColor) : mode === 'dark' ? ACCENT_PRESETS[prefs.accent].dark : ACCENT_PRESETS[prefs.accent].light;

  return (
    <div>
      {/* Live Preview & Reset */}
      <div className="tcx-set-section">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <h3>Live preview</h3>
            <p className="mt-1 text-[13px] text-[var(--tcx-muted)]">Changes apply immediately across the workspace and save in this browser.</p>
          </div>
          <Button
            icon={<Icon name="refresh" size={14} />}
            onClick={() => {
              resetPrefs();
              message.success('Appearance reset to defaults');
            }}
          >
            Reset to defaults
          </Button>
        </div>

        <div className="mt-3 overflow-hidden border border-[var(--tcx-border)] bg-[var(--tcx-bg)] p-3" style={{ borderRadius: 'var(--tcx-radius-card)' }}>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-[150px_1fr]">
            <div
              className="flex flex-col gap-1.5 border p-2.5"
              style={{
                background: 'var(--tcx-sider)',
                borderColor: 'var(--tcx-side-border)',
                borderRadius: 'var(--tcx-radius-control)',
              }}
            >
              <div className="flex items-center gap-2 pb-1">
                <span
                  className="grid h-5 w-5 place-items-center text-[11px] font-bold text-white"
                  style={{
                    background: 'var(--tcx-primary)',
                    borderRadius: 'var(--tcx-radius-sm)',
                  }}
                >
                  T
                </span>
                <span className="truncate text-[11.5px] font-semibold" style={{ color: 'var(--tcx-side-brand)' }}>
                  TechCMantix
                </span>
              </div>
              <div
                className="px-2 py-1 text-[11px] font-semibold"
                style={{
                  background: 'var(--tcx-primary)',
                  color: 'var(--tcx-on-primary)',
                  borderRadius: 'var(--tcx-radius-sm)',
                }}
              >
                Dashboard
              </div>
              <div className="px-2 py-1 text-[11px]" style={{ color: 'var(--tcx-side-text)' }}>
                Leads · Deals
              </div>
            </div>

            <div className="flex flex-col justify-between gap-2.5 border border-[var(--tcx-border)] bg-[var(--tcx-surface)] p-3" style={{ borderRadius: 'var(--tcx-radius-control)' }}>
              <div className="flex flex-wrap items-center justify-between gap-2">
                <div>
                  <div className="text-[13px] font-bold text-[var(--tcx-text)]">Q4 Enterprise Renewal</div>
                  <div className="text-[11.5px] text-[var(--tcx-muted)]">₹18,50,000 · Proposal stage · Next call tomorrow</div>
                </div>
                <div className="flex items-center gap-2">
                  <Button size="small">Edit</Button>
                  <Button size="small" type="primary">
                    Primary action
                  </Button>
                </div>
              </div>
              <div className="flex flex-wrap items-center gap-2 border-t border-[var(--tcx-border)] pt-2 text-[11.5px]">
                <span
                  className="px-2 py-0.5 font-semibold"
                  style={{
                    background: 'var(--tcx-primary-soft)',
                    color: 'var(--tcx-primary-text)',
                    borderRadius: 'var(--tcx-radius-sm)',
                  }}
                >
                  Accent badge
                </span>
                <span className="text-[var(--tcx-muted)]">
                  Shape: <b className="text-[var(--tcx-text)]">{prefs.radius}</b>
                </span>
                <span className="text-[var(--tcx-muted)]">·</span>
                <span className="text-[var(--tcx-muted)]">
                  Text: <b className="text-[var(--tcx-text)]">{prefs.fontScale.toUpperCase()}</b>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Theme Mode */}
      <div className="tcx-set-section">
        <h3>Theme mode</h3>
        <p>Match your operating system or lock Light or Dark mode.</p>
        <div className="tcx-theme-cards" role="radiogroup" aria-label="Theme">
          {THEME_CARDS.map((card) => (
            <button key={card.value} type="button" role="radio" aria-checked={prefs.theme === card.value} className="tcx-theme-card" onClick={() => updatePrefs({ theme: card.value })}>
              <span className={`tcx-theme-prev ${card.prevClass}`}>
                {card.prevClass === 'sys' ? null : (
                  <>
                    <span className="s" />
                    <span className="m">
                      <i />
                      <i />
                      <i style={{ width: '70%' }} />
                    </span>
                  </>
                )}
              </span>
              {card.label}
            </button>
          ))}
        </div>
      </div>

      {/* Accent Color + Custom Picker */}
      <div className="tcx-set-section">
        <h3>Accent color</h3>
        <p>Used for primary buttons, active navigation items, links, and focus rings.</p>
        <div className="tcx-swatches" role="radiogroup" aria-label="Accent color">
          {ACCENT_ORDER.map((key) => {
            const preset = ACCENT_PRESETS[key];
            return <button key={key} type="button" role="radio" aria-checked={prefs.accent === key} aria-label={preset.label} title={preset.label} className="tcx-swatch" style={{ '--sw': preset.light } as React.CSSProperties} onClick={() => applyUpdate({ accent: key }, `Accent changed to ${preset.label}`)} />;
          })}

          <label
            className="inline-flex cursor-pointer items-center gap-2 border border-[var(--tcx-border-strong)] bg-[var(--tcx-surface)] px-2.5 py-1.5 text-[12.5px] font-medium text-[var(--tcx-text)]"
            style={{
              borderRadius: 'var(--tcx-radius-control)',
              boxShadow: prefs.accent === 'custom' ? '0 0 0 2px var(--tcx-primary-soft)' : undefined,
              borderColor: prefs.accent === 'custom' ? 'var(--tcx-primary)' : undefined,
            }}
          >
            <input
              type="color"
              aria-label="Pick custom accent color"
              value={normalizeHexColor(prefs.customColor)}
              onChange={(e) =>
                updatePrefs({
                  accent: 'custom',
                  customColor: normalizeHexColor(e.target.value),
                })
              }
              className="h-5 w-5 cursor-pointer rounded border-0 bg-transparent p-0"
            />
            <span>Custom</span>
            <code className="font-mono text-[11.5px] text-[var(--tcx-muted)]">{activeHex}</code>
          </label>
        </div>
      </div>

      {/* Sidebar Style & Default State */}
      <div className="tcx-set-section">
        <h3>Sidebar navigation</h3>
        <p>Choose the left rail color theme and default collapsed state.</p>

        <div className="tcx-set-row">
          <div className="t">
            <b>Sidebar color style</b>
            <span>Choose dark navy, pure charcoal, crisp white, or tinted.</span>
          </div>
          <Segmented
            value={prefs.sidebarStyle}
            onChange={(val) => updatePrefs({ sidebarStyle: val as SidebarStyle })}
            options={[
              { label: 'Navy', value: 'navy' },
              { label: 'Charcoal', value: 'charcoal' },
              { label: 'Light', value: 'light' },
              { label: 'Tinted', value: 'tinted' },
            ]}
          />
        </div>

        <div className="tcx-set-row">
          <div className="t">
            <b>Sidebar default view</b>
            <span>Save expanded labels or icon-only rail across reloads.</span>
          </div>
          <Segmented
            value={prefs.collapsed ? 'collapsed' : 'expanded'}
            onChange={(val) => updatePrefs({ collapsed: val === 'collapsed' })}
            options={[
              { label: 'Expanded', value: 'expanded' },
              { label: 'Collapsed', value: 'collapsed' },
            ]}
          />
        </div>
      </div>

      {/* Layout & Typography */}
      <div className="tcx-set-section">
        <h3>Layout &amp; typography</h3>
        <p>Customize corners, fonts, text size, and background tone.</p>

        <div className="tcx-set-row">
          <div className="t">
            <b>Corner shape</b>
            <span>Adjust roundness on cards, buttons, modals, and inputs.</span>
          </div>
          <Segmented
            value={prefs.radius}
            onChange={(val) => updatePrefs({ radius: val as RadiusStyle })}
            options={[
              { label: 'Sharp', value: 'sharp' },
              { label: 'Balanced', value: 'balanced' },
              { label: 'Rounded', value: 'rounded' },
            ]}
          />
        </div>

        <div className="tcx-set-row">
          <div className="t">
            <b>Font family</b>
            <span>Switch between Inter, IBM Plex Sans, or OS native font.</span>
          </div>
          <Segmented
            value={prefs.fontFamily}
            onChange={(val) => updatePrefs({ fontFamily: val as FontChoice })}
            options={[
              { label: 'Inter', value: 'inter' },
              { label: 'IBM Plex', value: 'ibm' },
              { label: 'System', value: 'system' },
            ]}
          />
        </div>

        <div className="tcx-set-row">
          <div className="t">
            <b>Text size</b>
            <span>Scale base workspace copy from 13 px to 15 px.</span>
          </div>
          <Segmented
            value={prefs.fontScale}
            onChange={(val) => updatePrefs({ fontScale: val as FontScale })}
            options={[
              { label: 'Small', value: 'sm' },
              { label: 'Medium', value: 'md' },
              { label: 'Large', value: 'lg' },
            ]}
          />
        </div>

        <div className="tcx-set-row">
          <div className="t">
            <b>Background &amp; contrast</b>
            <span>Cool slate backdrop, warm paper tint, or high contrast.</span>
          </div>
          <Segmented
            value={prefs.surfaceTone}
            onChange={(val) => updatePrefs({ surfaceTone: val as SurfaceTone })}
            options={[
              { label: 'Cool slate', value: 'slate' },
              { label: 'Warm paper', value: 'paper' },
              { label: 'High contrast', value: 'contrast' },
            ]}
          />
        </div>
      </div>
    </div>
  );
}
