// components/admin/page-builder/ModalEditPanel.tsx
'use client';

import { PageComponent, ComponentPropsByType, EditorProps } from '@/lib/page-builder/types';
import { componentRegistry } from '@/lib/page-builder/component-registry';
import { useState, useEffect, useCallback } from 'react';

interface ModalEditPanelProps {
  component: PageComponent | null;
  onSave: (id: string, newProps: PageComponent['props']) => void;
  onClose: () => void;
}

function ModalContent({
  component,
  onSave,
  onClose,
}: {
  component: PageComponent;
  onSave: (id: string, newProps: PageComponent['props']) => void;
  onClose: () => void;
}) {
  const [localProps, setLocalProps] = useState<PageComponent['props']>(component.props);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  const config = componentRegistry[component.type];
  const Editor = config?.editor;

  // Lock body scroll when modal opens
  useEffect(() => {
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = originalOverflow;
    };
  }, []);

  // Handle escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (hasUnsavedChanges) {
          if (window.confirm('You have unsaved changes. Are you sure you want to close?')) {
            onClose();
          }
        } else {
          onClose();
        }
      }
    };
    window.addEventListener('keydown', handleEscape);
    return () => window.removeEventListener('keydown', handleEscape);
  }, [hasUnsavedChanges, onClose]);

  const handleUpdate = useCallback((newProps: PageComponent['props']) => {
    setLocalProps(newProps);
    setHasUnsavedChanges(true);
  }, []);

  const handleSave = useCallback(() => {
    onSave(component.id, localProps);
    setHasUnsavedChanges(false);
    onClose();
  }, [component.id, localProps, onSave, onClose]);

  const handleClose = useCallback(() => {
    if (hasUnsavedChanges) {
      if (window.confirm('You have unsaved changes. Are you sure you want to close?')) {
        onClose();
      }
    } else {
      onClose();
    }
  }, [hasUnsavedChanges, onClose]);

  const handleBackdropClick = useCallback((e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      handleClose();
    }
  }, [handleClose]);

  const renderEditor = () => {
    if (!Editor) {
      return (
        <div className="text-center py-12">
          <div className="w-16 h-16 bg-var-surface-hover rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-8 h-8 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h3 className="text-lg font-medium text-var-text mb-2">No Editor Available</h3>
          <p className="text-var-text-muted max-w-sm mx-auto">
            This component does not have a custom editor interface yet.
          </p>
        </div>
      );
    }

    const TypedEditor = Editor as React.ComponentType<EditorProps<ComponentPropsByType[typeof component.type]>>;
    const typedProps = localProps as ComponentPropsByType[typeof component.type];

    return <TypedEditor props={typedProps} onUpdate={handleUpdate} />;
  };

  return (
    <div
      className="fixed inset-0 bg-black/70 flex items-center justify-center p-4 z-50"
      onClick={handleBackdropClick}
    >
      <div
        className="bg-var-surface rounded-xl shadow-var-modal w-full max-w-2xl max-h-[85vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-var-border bg-var-surface rounded-t-xl shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-var-primary-muted rounded-lg flex items-center justify-center">
              <span className="text-sm">{config?.icon}</span>
            </div>
            <div>
              <h2 className="text-lg font-semibold text-var-text">Edit {component.type}</h2>
              <p className="text-sm text-var-text-muted">{config?.description}</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {hasUnsavedChanges && (
              <span className="text-xs bg-var-warning-bg text-var-warning-text px-2 py-1 rounded-full font-medium">
                Unsaved
              </span>
            )}
            <button
              onClick={handleClose}
              className="w-8 h-8 flex items-center justify-center text-var-text-muted hover:text-var-text hover:bg-var-surface-hover rounded-lg transition-colors"
              aria-label="Close"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        {/* Editor Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {renderEditor()}
        </div>

        {/* Footer */}
        <div className="border-t border-var-border p-6 bg-var-surface-hover rounded-b-xl shrink-0">
          <div className="flex justify-end gap-3">
            <button
              onClick={handleClose}
              className="px-5 py-2 border border-var-border text-var-text-secondary rounded-lg hover:bg-var-surface-hover transition-colors font-medium text-sm"
            >
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={!hasUnsavedChanges}
              className={`inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card ${
                hasUnsavedChanges
                  ? 'bg-var-primary text-white hover:bg-var-primary-hover shadow-var-card'
                  : 'bg-var-surface-hover text-var-text-muted cursor-not-allowed'
              }`}
            >
              Save Changes
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export function ModalEditPanel({ component, onSave, onClose }: ModalEditPanelProps) {
  if (!component) return null;
  // Use a unique key to remount the component when the component changes
  return <ModalContent key={component.id} component={component} onSave={onSave} onClose={onClose} />;
}