'use client';

import { useState, useEffect } from 'react';
import { RESERVED_SLUGS } from '@/lib/custom-pages';

interface NavItem {
  id: number;
  label: string;
  itemType: string;
  menuLocation: string;
  parentId: number | null;
  parentCategory: string | null;
}

interface Category {
  id: string;
  name: string;
  slug: string;
}

interface CreatePageModalProps {
  onClose: () => void;
  onSuccess: (slug: string) => void;
}

export function CreatePageModal({ onClose, onSuccess }: CreatePageModalProps) {
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [metaTitle, setMetaTitle] = useState('');
  const [metaDescription, setMetaDescription] = useState('');
  const [showInHeader, setShowInHeader] = useState(true);
  const [showInFooter, setShowInFooter] = useState(false);
  const [parentSelection, setParentSelection] = useState('');
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [error, setError] = useState('');
  const [items, setItems] = useState<NavItem[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);

  useEffect(() => {
    const loadData = async () => {
      try {
        const [itemsRes, catsRes] = await Promise.all([
          fetch('/api/navigation-items?all=1'),
          fetch('/api/editor/categories')
        ]);
        const itemsJson = await itemsRes.json();
        const catsJson = await catsRes.json();
        setItems(itemsJson.items || []);
        setCategories(catsJson.categories || []);
      } catch (err) {
        console.error('Failed to load nav data', err);
      } finally {
        setInitialLoading(false);
      }
    };
    loadData();
  }, []);

  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTitle = e.target.value;
    setTitle(newTitle);
    
    // Auto-generate slug
    const generatedSlug = newTitle
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)+/g, '');
    setSlug(generatedSlug);
  };

  const handleSlugChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value;
    const clean = raw.toLowerCase().replace(/[^a-z0-9\-]/g, '');
    setSlug(clean);
  };

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

    if (!title || !slug) {
      setError('Title and Slug are required.');
      return;
    }

    if (RESERVED_SLUGS.includes(slug)) {
      setError(`Slug '${slug}' is reserved and cannot be used.`);
      return;
    }

    setLoading(true);
    try {
      // 1. Create custom page
      const resPage = await fetch('/api/custom-pages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title,
          slug,
          metaTitle,
          metaDescription,
          showInHeader,
          showInFooter
        })
      });

      const pageData = await resPage.json();
      if (!resPage.ok) throw new Error(pageData.error || 'Failed to create page');

      const sourceId = pageData.id.toString();

      // 2. Create navigation items based on checkboxes
      let parentId: number | null = null;
      let parentCategory: string | null = null;
      if (parentSelection) {
        if (parentSelection.startsWith('cat_')) {
          parentCategory = parentSelection.replace('cat_', '');
        } else if (parentSelection.startsWith('parent_')) {
          parentId = parseInt(parentSelection.replace('parent_', ''), 10);
        }
      }

      if (showInHeader) {
        await fetch('/api/navigation-items', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            label: title,
            url: `/${slug}`,
            itemType: 'custom_page',
            sourceId,
            menuLocation: 'top_header',
            parentId,
            parentCategory
          })
        });
      }

      if (showInFooter) {
        await fetch('/api/navigation-items', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            label: title,
            url: `/${slug}`,
            itemType: 'custom_page',
            sourceId,
            menuLocation: 'footer',
            parentId,
            parentCategory
          })
        });
      }

      onSuccess(slug);
    } 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">Create New Page</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={handleTitleChange} 
              className="w-full border p-2 rounded outline-none focus:border-blue-500" 
              required
              placeholder="e.g. Special Offers"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">URL Slug</label>
            <div className="flex items-center border rounded overflow-hidden focus-within:border-blue-500">
              <span className="bg-gray-100 px-3 py-2 text-gray-500 text-sm border-r">/</span>
              <input 
                type="text" 
                value={slug} 
                onChange={handleSlugChange} 
                className="w-full p-2 outline-none" 
                required
                placeholder="special-offers"
              />
            </div>
          </div>

          <div className="border-t pt-4 mt-2">
            <h3 className="font-semibold text-sm mb-2 text-gray-700">SEO Settings (Optional)</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="border-t pt-4 mt-2">
            <h3 className="font-semibold text-sm mb-2 text-gray-700">Navigation Settings</h3>
            <div className="flex flex-col gap-2">
              <label className="flex items-center gap-2 text-sm">
                <input 
                  type="checkbox" 
                  checked={showInHeader} 
                  onChange={e => setShowInHeader(e.target.checked)} 
                />
                Show in Top Header
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input 
                  type="checkbox" 
                  checked={showInFooter} 
                  onChange={e => setShowInFooter(e.target.checked)} 
                />
                Show in Footer
              </label>

              <div className="mt-2">
                <label className="block text-sm font-medium mb-1">Parent Menu (Optional)</label>
                <p className="text-xs text-gray-500 mb-2">💡 For nesting to work, pick a parent from the same location selected above.</p>
                <select 
                  className="w-full border p-2 rounded outline-none text-sm focus:border-blue-500"
                  value={parentSelection}
                  onChange={e => setParentSelection(e.target.value)}
                  disabled={initialLoading}
                >
                  <option value="">None (Top Level)</option>
                  {categories.length > 0 && (
                    <optgroup label="🔒 Ranktraction Categories (Top Header)">
                      {categories.map(c => (
                        <option key={`c-${c.id}`} value={`cat_${c.slug}`}>{c.name}</option>
                      ))}
                    </optgroup>
                  )}
                  {items.filter(i => i.menuLocation === 'top_header' && i.itemType !== 'category').length > 0 && (
                    <optgroup label="Custom Pages / Links (Top Header)">
                      {items.filter(i => i.menuLocation === 'top_header' && i.itemType !== 'category').map(i => (
                        <option key={`pt-${i.id}`} value={`parent_${i.id}`}>
                          {i.parentId || i.parentCategory ? `— ${i.label}` : i.label}
                        </option>
                      ))}
                    </optgroup>
                  )}
                  {items.filter(i => i.menuLocation === 'footer' && i.itemType !== 'category').length > 0 && (
                    <optgroup label="Custom Pages / Links (Footer)">
                      {items.filter(i => i.menuLocation === 'footer' && i.itemType !== 'category').map(i => (
                        <option key={`pf-${i.id}`} value={`parent_${i.id}`}>
                          {i.parentId || i.parentCategory ? `— ${i.label}` : i.label}
                        </option>
                      ))}
                    </optgroup>
                  )}
                </select>
              </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 ? 'Creating...' : 'Create Page'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
