'use client';

import { useState, useEffect } from 'react';

interface PageSettingsModalProps {
  pageId: number;
  initialTitle: string;
  initialMetaTitle: string;
  initialMetaDescription: string;
  onClose: () => void;
  onSuccess: () => void;
}

export function PageSettingsModal({ 
  pageId, 
  initialTitle, 
  initialMetaTitle, 
  initialMetaDescription, 
  onClose, 
  onSuccess 
}: PageSettingsModalProps) {
  const [title, setTitle] = useState(initialTitle);
  const [metaTitle, setMetaTitle] = useState(initialMetaTitle);
  const [metaDescription, setMetaDescription] = useState(initialMetaDescription);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!title) {
      setError('Page Name is required.');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch('/api/custom-pages', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: pageId,
          title,
          metaTitle,
          metaDescription,
        })
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update page settings');

      onSuccess();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
      <div className="bg-white p-6 rounded-lg shadow-xl w-full max-w-md max-h-[90vh] overflow-y-auto">
        <h2 className="text-xl font-bold mb-4 text-gray-800">Page Settings</h2>
        {error && <div className="mb-4 text-red-500 text-sm">{error}</div>}
        <form onSubmit={handleSubmit} className="flex flex-col gap-4 text-gray-800">
          <div>
            <label className="block text-sm font-medium mb-1">Page Name</label>
            <input 
              type="text" 
              value={title} 
              onChange={e => setTitle(e.target.value)} 
              className="w-full border p-2 rounded outline-none focus:border-blue-500" 
              required
            />
          </div>

          <div className="border-t pt-4 mt-2">
            <h3 className="font-semibold text-sm mb-2 text-gray-700">SEO Settings</h3>
            <div className="flex flex-col gap-3">
              <div>
                <label className="block text-xs font-medium mb-1">Meta Title</label>
                <input 
                  type="text" 
                  value={metaTitle} 
                  onChange={e => setMetaTitle(e.target.value)} 
                  className="w-full border p-2 rounded outline-none text-sm focus:border-blue-500" 
                  placeholder={title || 'Page Meta Title'}
                />
              </div>
              <div>
                <label className="block text-xs font-medium mb-1">Meta Description</label>
                <textarea 
                  value={metaDescription} 
                  onChange={e => setMetaDescription(e.target.value)} 
                  className="w-full border p-2 rounded outline-none text-sm h-20 focus:border-blue-500" 
                  placeholder="Page description for search engines"
                />
              </div>
            </div>
          </div>

          <div className="flex justify-end gap-3 mt-4">
            <button type="button" onClick={onClose} className="px-4 py-2 border rounded text-sm hover:bg-gray-50">Cancel</button>
            <button type="submit" disabled={loading} className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50">
              {loading ? 'Saving...' : 'Save Settings'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
