import { useState, useEffect } from 'react';

interface FrontmatterEditorProps {
  frontmatter: Record<string, any>;
  onChange: (frontmatter: Record<string, any>) => void;
  className?: string;
}

export function FrontmatterEditor({ frontmatter, onChange, className = '' }: FrontmatterEditorProps) {
  const [fields, setFields] = useState<Record<string, any>>(frontmatter || {});
  const [newKey, setNewKey] = useState('');
  const [newValue, setNewValue] = useState('');

  useEffect(() => {
    setFields(frontmatter || {});
  }, [frontmatter]);

  const updateField = (key: string, value: any) => {
    const updated = { ...fields, [key]: value };
    setFields(updated);
    onChange(updated);
  };

  const deleteField = (key: string) => {
    const updated = { ...fields };
    delete updated[key];
    setFields(updated);
    onChange(updated);
  };

  const addField = () => {
    if (!newKey.trim()) return;
    
    const updated = { ...fields, [newKey]: newValue };
    setFields(updated);
    onChange(updated);
    setNewKey('');
    setNewValue('');
  };

  const inferType = (value: any): string => {
    if (Array.isArray(value)) return 'array';
    if (typeof value === 'boolean') return 'boolean';
    if (typeof value === 'number') return 'number';
    return 'string';
  };

  const renderFieldInput = (key: string, value: any) => {
    const type = inferType(value);

    switch (type) {
      case 'boolean':
        return (
          <input
            type="checkbox"
            checked={value}
            onChange={(e) => updateField(key, e.target.checked)}
            className="w-5 h-5 text-amber-600 border-2 border-gray-900 focus:ring-0 focus:ring-offset-0"
          />
        );

      case 'array':
        return (
          <input
            type="text"
            value={Array.isArray(value) ? value.join(', ') : ''}
            onChange={(e) => updateField(key, e.target.value.split(',').map((v) => v.trim()))}
            className="flex-1 px-3 py-2 border-2 border-gray-900 bg-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-amber-500"
            placeholder="comma, separated, values"
          />
        );

      case 'number':
        return (
          <input
            type="number"
            value={value}
            onChange={(e) => updateField(key, parseFloat(e.target.value) || 0)}
            className="flex-1 px-3 py-2 border-2 border-gray-900 bg-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-amber-500"
          />
        );

      default:
        return (
          <input
            type="text"
            value={value}
            onChange={(e) => updateField(key, e.target.value)}
            className="flex-1 px-3 py-2 border-2 border-gray-900 bg-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-amber-500"
          />
        );
    }
  };

  return (
    <div className={`bg-amber-50 border-2 border-gray-900 p-6 ${className}`}>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold" style={{ fontFamily: 'Archivo Black, sans-serif' }}>
          Frontmatter
        </h3>
        <span className="text-xs text-gray-600 font-mono">YAML Metadata</span>
      </div>

      {Object.keys(fields).length === 0 ? (
        <div className="text-sm text-gray-600 italic mb-4 p-4 bg-white border-2 border-dashed border-gray-300">
          No frontmatter fields. Add one below.
        </div>
      ) : (
        <div className="space-y-3 mb-4">
          {Object.entries(fields).map(([key, value]) => (
            <div key={key} className="flex items-center gap-2">
              <div className="flex-1 grid grid-cols-2 gap-2">
                <div className="px-3 py-2 bg-gray-900 text-white font-mono text-sm font-semibold flex items-center">
                  {key}
                </div>
                {renderFieldInput(key, value)}
              </div>
              <button
                onClick={() => deleteField(key)}
                className="px-3 py-2 bg-red-600 text-white font-semibold hover:bg-red-700 transition-colors border-2 border-gray-900"
                title="Delete field"
              >
                ×
              </button>
            </div>
          ))}
        </div>
      )}

      <div className="border-t-2 border-gray-900 pt-4">
        <div className="text-sm font-semibold mb-2" style={{ fontFamily: 'Archivo Black, sans-serif' }}>
          Add Field
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            value={newKey}
            onChange={(e) => setNewKey(e.target.value)}
            placeholder="Key (e.g., title)"
            className="flex-1 px-3 py-2 border-2 border-gray-900 bg-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-amber-500"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && newKey.trim()) {
                addField();
              }
            }}
          />
          <input
            type="text"
            value={newValue}
            onChange={(e) => setNewValue(e.target.value)}
            placeholder="Value"
            className="flex-1 px-3 py-2 border-2 border-gray-900 bg-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-amber-500"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && newKey.trim()) {
                addField();
              }
            }}
          />
          <button
            onClick={addField}
            disabled={!newKey.trim()}
            className="px-4 py-2 bg-gray-900 text-white font-semibold hover:bg-gray-800 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors border-2 border-gray-900"
          >
            + Add
          </button>
        </div>
      </div>
    </div>
  );
}
