import { useState, useEffect } from 'react';
import { useSettingsStore, Settings } from '../store/settingsStore';

const clampValue = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

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

export function SettingsPanel({ open, onClose }: SettingsPanelProps) {
  const { settings, fetchSettings, updateSettings } = useSettingsStore();

  const [workMins, setWorkMins] = useState(25);
  const [shortBreakMins, setShortBreakMins] = useState(5);
  const [longBreakMins, setLongBreakMins] = useState(15);
  const [sessionsBeforeLong, setSessionsBeforeLong] = useState(4);

  useEffect(() => {
    if (open && !settings) {
      fetchSettings();
    }
  }, [open, settings, fetchSettings]);

  useEffect(() => {
    if (settings) {
      setWorkMins(clampValue(Math.round(settings.work_duration_secs / 60), 1, 120));
      setShortBreakMins(clampValue(Math.round(settings.short_break_secs / 60), 1, 60));
      setLongBreakMins(clampValue(Math.round(settings.long_break_secs / 60), 1, 60));
      setSessionsBeforeLong(clampValue(settings.sessions_before_long_break, 1, 10));
    }
  }, [settings]);

  if (!open) return null;

  const handleSave = async () => {
    const nextWorkMins = clampValue(workMins, 1, 120);
    const nextShortBreakMins = clampValue(shortBreakMins, 1, 60);
    const nextLongBreakMins = clampValue(longBreakMins, 1, 60);
    const nextSessionsBeforeLong = clampValue(sessionsBeforeLong, 1, 10);

    setWorkMins(nextWorkMins);
    setShortBreakMins(nextShortBreakMins);
    setLongBreakMins(nextLongBreakMins);
    setSessionsBeforeLong(nextSessionsBeforeLong);

    const s: Settings = {
      work_duration_secs: nextWorkMins * 60,
      short_break_secs: nextShortBreakMins * 60,
      long_break_secs: nextLongBreakMins * 60,
      sessions_before_long_break: nextSessionsBeforeLong,
    };
    await updateSettings(s);
    onClose();
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(11, 14, 19, 0.70)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 100,
      }}
    >
      {/* Modal card */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--ink-1)',
          border: '1px solid var(--line-2)',
          borderRadius: 'var(--r-3)',
          boxShadow: 'var(--shadow-3)',
          padding: '32px',
          width: 'min(360px, calc(100vw - 32px))',
          maxHeight: 'calc(100vh - 32px)',
          overflowY: 'auto',
          display: 'flex',
          flexDirection: 'column',
          gap: '24px',
        }}
      >
        <span className="eyebrow" style={{ letterSpacing: '0.18em' }}>
          Settings
        </span>

        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <NumberField
            label="Work duration"
            unit="min"
            value={workMins}
            min={1}
            max={120}
            onChange={setWorkMins}
          />
          <NumberField
            label="Short break"
            unit="min"
            value={shortBreakMins}
            min={1}
            max={60}
            onChange={setShortBreakMins}
          />
          <NumberField
            label="Long break"
            unit="min"
            value={longBreakMins}
            min={1}
            max={60}
            onChange={setLongBreakMins}
          />
          <NumberField
            label="Sessions before long break"
            unit="sessions"
            value={sessionsBeforeLong}
            min={1}
            max={10}
            onChange={setSessionsBeforeLong}
          />
        </div>

        <span style={{ fontFamily: 'var(--font-sans)', fontSize: '12px', color: 'var(--fg-4)', lineHeight: 1.4 }}>
          Values are clamped to sensible minimums before saving.
        </span>

        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
          <button
            onClick={onClose}
            style={{
              fontFamily: 'var(--font-sans)',
              fontSize: '14px',
              fontWeight: 500,
              padding: '8px 16px',
              borderRadius: 'var(--r-1)',
              border: '1px solid var(--line-2)',
              background: 'transparent',
              color: 'var(--brass)',
              cursor: 'pointer',
              transition: 'border-color 0.15s ease',
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'var(--brass)';
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'var(--line-2)';
            }}
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            style={{
              fontFamily: 'var(--font-sans)',
              fontSize: '14px',
              fontWeight: 600,
              padding: '8px 20px',
              borderRadius: 'var(--r-1)',
              border: 'none',
              background: 'var(--brass)',
              color: 'var(--brass-ink)',
              cursor: 'pointer',
              transition: 'background 0.15s ease',
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = 'var(--brass-bright)';
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = 'var(--brass)';
            }}
            onMouseDown={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = 'var(--brass-deep)';
            }}
            onMouseUp={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = 'var(--brass-bright)';
            }}
          >
            Save
          </button>
        </div>
      </div>
    </div>
  );
}

interface NumberFieldProps {
  label: string;
  unit: string;
  value: number;
  min: number;
  max: number;
  onChange: (v: number) => void;
}

function NumberField({ label, unit, value, min, max, onChange }: NumberFieldProps) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: '16px',
      }}
    >
      <label
        style={{
          fontFamily: 'var(--font-sans)',
          fontSize: '14px',
          color: 'var(--fg-2)',
          flex: 1,
        }}
      >
        {label}
      </label>
      <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
        <input
          type="number"
          min={min}
          max={max}
          value={value}
          onChange={(e) => onChange(clampValue(parseInt(e.target.value, 10) || min, min, max))}
          style={{
            fontFamily: 'var(--font-mono)',
            fontSize: '14px',
            fontVariantNumeric: 'tabular-nums',
            padding: '5px 8px',
            borderRadius: 'var(--r-2)',
            border: '1px solid var(--line-2)',
            background: 'var(--ink-3)',
            color: 'var(--fg-1)',
            outline: 'none',
            width: '56px',
            textAlign: 'center',
          }}
          onFocus={(e) => {
            (e.currentTarget as HTMLInputElement).style.boxShadow = 'var(--shadow-brass)';
          }}
          onBlur={(e) => {
            (e.currentTarget as HTMLInputElement).style.boxShadow = 'none';
          }}
        />
        <span
          style={{
            fontFamily: 'var(--font-sans)',
            fontSize: '12px',
            color: 'var(--fg-4)',
            minWidth: '44px',
          }}
        >
          {unit}
        </span>
      </div>
    </div>
  );
}
