import { useState, useEffect } from 'react';

export default function BlockedTimeManager() {
  const [blocks, setBlocks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_list_blocks', params: {} }, '*');
  }, []);

  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data.type === 'mcp-result') {
        const result = JSON.parse(e.data.result);
        setBlocks(result);
        setLoading(false);
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  const deleteBlock = (id: number) => {
    if (!confirm('Delete this blocked time?')) return;
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_delete_block', params: { id } }, '*');
    setTimeout(() => window.location.reload(), 500);
  };

  if (loading) return <div style={{ padding: '20px' }}>Loading...</div>;

  return (
    <div style={{ padding: '20px', fontFamily: 'system-ui, sans-serif' }}>
      <header style={{ marginBottom: '20px' }}>
        <h1 style={{ margin: 0, fontSize: '24px' }}>Blocked Time Manager</h1>
      </header>

      <section style={{ marginBottom: '30px' }}>
        <h2 style={{ fontSize: '18px', marginBottom: '10px' }}>Current Blocks</h2>
        <div style={{ display: 'grid', gap: '10px' }}>
          {blocks.map((block: any) => (
            <div key={block.id} style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px' }}>
              <div style={{ marginBottom: '5px' }}><strong>Start:</strong> {block.start}</div>
              <div style={{ marginBottom: '5px' }}><strong>End:</strong> {block.end}</div>
              {block.notes && <div style={{ marginBottom: '5px' }}><strong>Notes:</strong> {block.notes}</div>}
              <button onClick={() => deleteBlock(block.id)} style={{ marginTop: '10px', padding: '8px 16px', background: '#dc3545', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>Delete</button>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}
