import React, { useState } from 'react';
import { BackgroundEntryEditor } from './BackgroundEntryEditor';
import { ParseErrorEntryEditor } from './ParseErrorEntryEditor';
import { ReadEntryEditor } from './ReadEntryEditor';
import { ReasoningEntryEditor } from './ReasoningEntryEditor';
import { RepeatEntryEditor } from './RepeatEntryEditor';
import { SingleEntryEditor } from './SingleEntryEditor';
import { WriteEntryEditor } from './WriteEntryEditor';

const EntryTypes = {
  BACKGROUND: 'background',
  PARSE_ERROR: 'parse_error',
  READ_STDIN: 'read_stdin',
  REASONING: 'reasoning',
  REPEAT: 'repeat',
  SINGLE: 'single',
  WRITE: 'write'
};

const EntryEditors = {
  [EntryTypes.BACKGROUND]: BackgroundEntryEditor,
  [EntryTypes.PARSE_ERROR]: ParseErrorEntryEditor,
  [EntryTypes.READ_STDIN]: ReadEntryEditor,
  [EntryTypes.REASONING]: ReasoningEntryEditor,
  [EntryTypes.REPEAT]: RepeatEntryEditor,
  [EntryTypes.SINGLE]: SingleEntryEditor,
  [EntryTypes.WRITE]: WriteEntryEditor
};

export const MemoryEditor = ({
  entries = [],
  onCreateEntry,
  onSaveEntry,
  onDeleteEntry,
  onResetEntry,
  onUpdateEntry
}) => {
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [selectedType, setSelectedType] = useState(EntryTypes.SINGLE);

  const handleCreate = (_id, entry) => {
    onCreateEntry(entry);
    setShowCreateDialog(false);
  };

  const generateId = () => {
    const now = new Date();
    return now.getFullYear() +
      String(now.getMonth() + 1).padStart(2, '0') +
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') +
      String(now.getMinutes()).padStart(2, '0') +
      String(now.getSeconds()).padStart(2, '0') + '_' +
      String(now.getMilliseconds()).padStart(3, '0');
  };

  const getInitialEntry = (type) => {
    const baseEntry = {
      type: type,
      id: generateId()
    };

    switch (type) {
      case EntryTypes.BACKGROUND:
      case EntryTypes.REPEAT:
      case EntryTypes.SINGLE:
        return {
          ...baseEntry,
          script: '',
          timeout: null,
          limit: null
        };
      case EntryTypes.PARSE_ERROR:
        return {
          ...baseEntry,
          content: '',
          error: ''
        };
      case EntryTypes.READ_STDIN:
        return {
          ...baseEntry,
          content: '',
          read: false
        };
      case EntryTypes.REASONING:
        return {
          ...baseEntry,
          content: ''
        };
      case EntryTypes.WRITE:
        return {
          ...baseEntry,
          content: '',
          written: false
        };
      default:
        return baseEntry;
    }
  };

  const renderCreateDialog = () => {
    const EditorComponent = EntryEditors[selectedType];
    const entry = getInitialEntry(selectedType);

    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
        <div className="bg-white p-4 rounded-lg max-w-2xl w-full m-4">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-medium">Create New Entry</h2>
            <button 
              onClick={() => setShowCreateDialog(false)}
              className="text-gray-500 hover:text-gray-700"
            >
              ✕
            </button>
          </div>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700">Entry Type</label>
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
            >
              {Object.entries(EntryTypes).map(([key, value]) => (
                <option key={value} value={value}>
                  {key.toLowerCase().replace('_', ' ')}
                </option>
              ))}
            </select>
          </div>
          <EditorComponent
            entry={entry}
            isNew={true}
            onSave={handleCreate}
            onCancel={() => setShowCreateDialog(false)}
          />
        </div>
      </div>
    );
  };

  const renderEntry = (entry) => {
    const EditorComponent = EntryEditors[entry.type];
    if (!EditorComponent) {
      console.warn(`Unknown entry type: ${entry.type}`);
      return null;
    }

    return (
      <EditorComponent
        key={entry.id}
        entry={entry}
        onSave={onSaveEntry}
        onDelete={onDeleteEntry}
        onReset={onResetEntry}
        onUpdate={onUpdateEntry}
      />
    );
  };

  return (
    <div className="p-4">
      <div className="flex justify-end mb-4">
        <button
          onClick={() => setShowCreateDialog(true)}
          className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700"
        >
          Add Entry
        </button>
      </div>

      <div className="space-y-4">
        {entries.map(renderEntry)}
      </div>

      {showCreateDialog && renderCreateDialog()}
    </div>
  );
};

export default MemoryEditor;
