/**
 * BorderRadiusFieldEditor
 * Unified border-radius template:
 * - Supports global linking (effects.borderRadius*)
 * - Supports per-corner editing + link/unlink corners
 * - Serializes custom values as 4-value CSS shorthand: "tl tr br bl"
 *
 * Protocol rule: ALWAYS use this component for border-radius controllers.
 */
import { useMemo } from 'react';
import { t } from '@/lib/i18n';
import { Link2, Unlink2 } from 'lucide-react';
import { BorderRadiusEditor, BorderRadiusValue } from './BorderRadiusEditor';
import { FieldValue, PresetGlobalValues, createCustomValue, createGlobalRef, createDefaultRef, resolveFieldValue } from '../../types/appearance';

function isDefaultRef(v: unknown): v is { type: 'default' } {
  return !!v && typeof v === 'object' && (v as { type?: unknown }).type === 'default';
}

type RadiusGlobalKey =
  | 'effects.borderRadiusSmall'
  | 'effects.borderRadiusMedium'
  | 'effects.borderRadiusLarge'
  | 'effects.borderRadiusFull'
  | 'effects.borderRadiusCircle';

function isGlobalRef(v: unknown): v is { type: 'global'; ref: string } {
  return !!v && typeof v === 'object' && (v as { type?: unknown }).type === 'global' && typeof (v as { ref?: unknown }).ref === 'string';
}

function isCustomValue(v: unknown): v is { type: 'custom'; value: string } {
  return !!v && typeof v === 'object' && (v as { type?: unknown }).type === 'custom' && typeof (v as { value?: unknown }).value === 'string';
}

function isCornerObject(v: unknown): v is BorderRadiusValue {
  if (!v || typeof v !== 'object') return false;
  const o = v as Record<string, unknown>;
  return (
    typeof o.topLeft === 'string' &&
    typeof o.topRight === 'string' &&
    typeof o.bottomRight === 'string' &&
    typeof o.bottomLeft === 'string'
  );
}

/**
 * Parse CSS border-radius shorthand into 4 corners (tl tr br bl)
 * Supports 1-4 tokens, following CSS expansion rules.
 */
export function parseBorderRadiusShorthand(input: string | undefined): BorderRadiusValue {
  const raw = (input || '').trim();
  if (!raw) {
    return { topLeft: '0px', topRight: '0px', bottomRight: '0px', bottomLeft: '0px' };
  }
  const tokens = raw.split(/\s+/).filter(Boolean);
  if (tokens.length === 1) {
    const v = tokens[0];
    return { topLeft: v, topRight: v, bottomRight: v, bottomLeft: v };
  }
  if (tokens.length === 2) {
    const [a, b] = tokens;
    // tl/br = a, tr/bl = b
    return { topLeft: a, topRight: b, bottomRight: a, bottomLeft: b };
  }
  if (tokens.length === 3) {
    const [tl, tr_bl, br] = tokens;
    return { topLeft: tl, topRight: tr_bl, bottomRight: br, bottomLeft: tr_bl };
  }
  const [tl, tr, br, bl] = tokens;
  return { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl };
}

export function serializeBorderRadiusShorthand(value: BorderRadiusValue): string {
  // Always 4 tokens for protocol consistency
  return `${value.topLeft} ${value.topRight} ${value.bottomRight} ${value.bottomLeft}`.trim();
}

export function resolveBorderRadiusToShorthand(
  value: FieldValue | BorderRadiusValue | string | undefined,
  globalValues: PresetGlobalValues,
  fallback: string = '0px 0px 0px 0px'
): string {
  if (typeof value === 'string') {
    const v = parseBorderRadiusShorthand(value);
    return serializeBorderRadiusShorthand(v);
  }
  if (isCornerObject(value)) {
    return serializeBorderRadiusShorthand(value);
  }
  if (isGlobalRef(value) || isCustomValue(value)) {
    const resolved = resolveFieldValue(value as FieldValue, globalValues);
    const v = parseBorderRadiusShorthand(resolved);
    return serializeBorderRadiusShorthand(v);
  }
  const v = parseBorderRadiusShorthand(fallback);
  return serializeBorderRadiusShorthand(v);
}

interface BorderRadiusFieldEditorProps {
  label?: string;
  value: FieldValue | BorderRadiusValue | undefined;
  globalValues: PresetGlobalValues;
  onChange: (value: FieldValue) => void;
  disabled?: boolean;
  /** Default global ref used when linking for the first time (legacy) */
  defaultGlobalRef?: RadiusGlobalKey;
  /** True when editing the default preset — no toggle, field is always concrete */
  isDefaultPreset?: boolean;
  /** Resolved value from the default preset for this field (for display in toggle) */
  defaultPresetValue?: string;
}

export function BorderRadiusFieldEditor({
  label = t('Border Radius'),
  value,
  globalValues,
  onChange,
  disabled = false,
  defaultGlobalRef = 'effects.borderRadiusMedium',
  isDefaultPreset = false,
  defaultPresetValue,
}: BorderRadiusFieldEditorProps) {
  const isLinkedToGlobal = isGlobalRef(value);
  const isLinkedToDefPreset = isDefaultRef(value);

  const currentCorners: BorderRadiusValue = useMemo(() => {
    if (isCornerObject(value)) return value;
    if (isDefaultRef(value)) return parseBorderRadiusShorthand(defaultPresetValue || '8px');
    if (isCustomValue(value)) return parseBorderRadiusShorthand(value.value);
    if (isGlobalRef(value)) {
      const resolved = resolveFieldValue(value as FieldValue, globalValues);
      return parseBorderRadiusShorthand(resolved);
    }
    return parseBorderRadiusShorthand('8px');
  }, [value, globalValues, defaultPresetValue]);

  const handleCornersChange = (corners: BorderRadiusValue) => {
    onChange(createCustomValue(serializeBorderRadiusShorthand(corners)));
  };

  const toggleLink = () => {
    if (isLinkedToGlobal) {
      const shorthand = resolveBorderRadiusToShorthand(value as FieldValue, globalValues, '8px');
      onChange(createCustomValue(shorthand));
      return;
    }
    if (isLinkedToDefPreset) {
      onChange(createCustomValue(defaultPresetValue || '8px 8px 8px 8px'));
      return;
    }
    if (!isDefaultPreset) {
      onChange(createDefaultRef());
    } else {
      onChange(createGlobalRef(defaultGlobalRef));
    }
  };

  const showToggle = !isDefaultPreset || isLinkedToGlobal;

  return (
    <div className="space-y-2" dir="rtl">
      <div className="flex items-center justify-between gap-3">
        <label className="text-sm font-medium text-gray-700">{label}</label>
        {showToggle && (
          <button
            type="button"
            onClick={toggleLink}
            disabled={disabled}
            className={[
              'p-2 rounded-md border transition-colors',
              (isLinkedToGlobal || isLinkedToDefPreset) ? 'bg-primary-50 border-primary-200 text-primary-700' : 'bg-white border-gray-200 text-gray-600',
              'hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed',
            ].join(' ')}
            title={(isLinkedToGlobal || isLinkedToDefPreset) ? t('Unlink') : t('Link to default')}
          >
            {(isLinkedToGlobal || isLinkedToDefPreset) ? <Link2 size={16} /> : <Unlink2 size={16} />}
          </button>
        )}
      </div>

      {isLinkedToDefPreset ? (
        <div className="px-3 py-2 bg-primary/5 rounded-lg border-2 border-dashed border-primary/30 text-center">
          <div className="text-xs font-medium text-primary">{t('Linked to default')}</div>
          {defaultPresetValue && (
            <div className="text-xs text-gray-500 mt-0.5">{defaultPresetValue}</div>
          )}
        </div>
      ) : isLinkedToGlobal ? (
        <div className="px-3 py-2 bg-primary/5 rounded-lg border-2 border-dashed border-primary/30 text-center">
          <div className="text-xs font-medium text-primary">{t('Linked to global')}</div>
          <div className="text-xs text-gray-500 mt-0.5">
            {resolveFieldValue(value as FieldValue, globalValues)}
          </div>
        </div>
      ) : (
        <BorderRadiusEditor value={currentCorners} onChange={handleCornersChange} disabled={disabled} />
      )}
    </div>
  );
}


