'use client';

import { useEffect } from 'react';

export interface AdvancedOptionsData {
  mood?: string;
  lighting?: string;
  cameraAngle?: string;
  negativePrompts?: string[];
}

interface AdvancedOptionsModalProps {
  isOpen: boolean;
  onClose: () => void;
  value: AdvancedOptionsData;
  onChange: (options: AdvancedOptionsData) => void;
  disabled?: boolean;
}

export function AdvancedOptionsModal({
  isOpen,
  onClose,
  value,
  onChange,
  disabled = false,
}: AdvancedOptionsModalProps) {
  // Close on Escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, onClose]);

  // Focus trap
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  if (!isOpen) return null;

  const updateValue = (key: keyof AdvancedOptionsData, newValue: any) => {
    onChange({ ...value, [key]: newValue });
  };

  const handleNegativePromptsChange = (text: string) => {
    const prompts = text
      .split(',')
      .map((p) => p.trim())
      .filter((p) => p.length > 0)
      .slice(0, 10); // Max 10 items
    updateValue('negativePrompts', prompts.length > 0 ? prompts : undefined);
  };

  const clearAll = () => {
    onChange({
      mood: undefined,
      lighting: undefined,
      cameraAngle: undefined,
      negativePrompts: undefined,
    });
  };

  const hasAnyOptions =
    value.mood ||
    value.lighting ||
    value.cameraAngle ||
    (value.negativePrompts && value.negativePrompts.length > 0);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-fade-in"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-labelledby="advanced-options-title"
    >
      <div
        className="w-full max-w-2xl bg-slate-900/95 backdrop-blur-sm border border-slate-700 rounded-2xl shadow-2xl max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="sticky top-0 bg-slate-900/95 backdrop-blur-sm border-b border-slate-700 px-6 py-4 flex items-center justify-between">
          <h2 id="advanced-options-title" className="text-xl font-semibold text-white">
            Advanced Options
          </h2>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-slate-800 hover:bg-slate-700 text-gray-400 hover:text-white flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-amber-500"
            aria-label="Close advanced options"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="px-6 py-5 space-y-4">
          {/* Mood */}
          <div>
            <label htmlFor="mood" className="block text-sm font-medium text-gray-300 mb-2">
              Mood
            </label>
            <input
              type="text"
              id="mood"
              value={value.mood || ''}
              onChange={(e) => updateValue('mood', e.target.value || undefined)}
              placeholder="e.g., peaceful, energetic, mysterious..."
              maxLength={100}
              disabled={disabled}
              className="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
              aria-describedby="mood-hint"
            />
            <p id="mood-hint" className="text-xs text-gray-500 mt-1">
              Max 100 characters
            </p>
          </div>

          {/* Lighting */}
          <div>
            <label htmlFor="lighting" className="block text-sm font-medium text-gray-300 mb-2">
              Lighting
            </label>
            <input
              type="text"
              id="lighting"
              value={value.lighting || ''}
              onChange={(e) => updateValue('lighting', e.target.value || undefined)}
              placeholder="e.g., golden hour, dramatic shadows, soft natural light..."
              maxLength={100}
              disabled={disabled}
              className="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
              aria-describedby="lighting-hint"
            />
            <p id="lighting-hint" className="text-xs text-gray-500 mt-1">
              Max 100 characters
            </p>
          </div>

          {/* Camera Angle */}
          <div>
            <label htmlFor="camera-angle" className="block text-sm font-medium text-gray-300 mb-2">
              Camera Angle
            </label>
            <input
              type="text"
              id="camera-angle"
              value={value.cameraAngle || ''}
              onChange={(e) => updateValue('cameraAngle', e.target.value || undefined)}
              placeholder="e.g., wide shot, close-up, bird's eye view..."
              maxLength={100}
              disabled={disabled}
              className="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
              aria-describedby="camera-angle-hint"
            />
            <p id="camera-angle-hint" className="text-xs text-gray-500 mt-1">
              Max 100 characters
            </p>
          </div>

          {/* Negative Prompts */}
          <div>
            <label
              htmlFor="negative-prompts"
              className="block text-sm font-medium text-gray-300 mb-2"
            >
              Negative Prompts
            </label>
            <textarea
              id="negative-prompts"
              value={value.negativePrompts?.join(', ') || ''}
              onChange={(e) => handleNegativePromptsChange(e.target.value)}
              placeholder="e.g., blurry, low quality, distorted..."
              disabled={disabled}
              rows={3}
              className="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none"
              aria-describedby="negative-prompts-hint"
            />
            <p id="negative-prompts-hint" className="text-xs text-gray-500 mt-1">
              Comma-separated list (max 10 items, 100 chars each)
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-900/95 backdrop-blur-sm border-t border-slate-700 px-6 py-4 flex items-center justify-between gap-4">
          {hasAnyOptions ? (
            <button
              onClick={clearAll}
              disabled={disabled}
              className="px-4 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-gray-300 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-amber-500"
            >
              Clear All
            </button>
          ) : (
            <div></div>
          )}
          <button
            onClick={onClose}
            className="px-6 py-2.5 rounded-lg bg-amber-600 text-white font-semibold hover:bg-amber-700 transition-all focus:outline-none focus:ring-2 focus:ring-amber-500"
          >
            Apply
          </button>
        </div>
      </div>
    </div>
  );
}
