// Simple Page Editor Component
import React, { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';

interface PageEditorProps {
    siteId: string;
    pageId?: string;
    initialData?: {
        name: string;
        route: string;
        html_content: string;
        meta_title?: string;
        meta_description?: string;
        status: string;
    };
    onSave?: (page: any) => void;
    onCancel?: () => void;
}

export default function PageEditor({ siteId, pageId, initialData, onSave, onCancel }: PageEditorProps) {
    const [formData, setFormData] = useState(initialData || {
        name: '',
        route: '/',
        html_content: '',
        meta_title: '',
        meta_description: '',
        status: 'draft'
    });

    const queryClient = useQueryClient();

    const saveMutation = useMutation({
        mutationFn: async (data: typeof formData) => {
            const url = pageId
                ? `/api/shim/pages/${pageId}`
                : `/api/shim/pages/create`;

            const method = pageId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${import.meta.env.PUBLIC_GOD_MODE_TOKEN || 'local-dev-token'}`
                },
                body: JSON.stringify({ ...data, site_id: siteId })
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || 'Failed to save page');
            }

            return response.json();
        },
        onSuccess: (page) => {
            queryClient.invalidateQueries({ queryKey: ['pages'] });
            if (onSave) onSave(page);
        }
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        saveMutation.mutate(formData);
    };

    const handlePreview = () => {
        if (pageId) {
            window.open(`/preview/page/${pageId}`, '_blank');
        } else {
            alert('Please save the page first to preview it');
        }
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6 max-w-4xl">

            {/* Name */}
            <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">
                    Page Name
                </label>
                <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                    required
                />
            </div>

            {/* Route */}
            <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">
                    Route (must start with /)
                </label>
                <input
                    type="text"
                    value={formData.route}
                    onChange={(e) => setFormData({ ...formData, route: e.target.value })}
                    className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                    pattern="^\/[a-z0-9-\/]*$"
                    placeholder="/about"
                    required
                />
                <p className="mt-1 text-xs text-slate-500">Example: /about, /contact, /services/web</p>
            </div>

            {/* HTML Content */}
            <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">
                    HTML Content
                </label>
                <textarea
                    value={formData.html_content}
                    onChange={(e) => setFormData({ ...formData, html_content: e.target.value })}
                    className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500 font-mono text-sm"
                    rows={15}
                    placeholder="<h1>Welcome</h1><p>Your content here...</p>"
                />
            </div>

            {/* SEO Section */}
            <div className="border-t border-slate-700 pt-6">
                <h3 className="text-lg font-semibold text-white mb-4">SEO (Optional)</h3>

                <div className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-slate-300 mb-2">
                            Meta Title (max 70 chars)
                        </label>
                        <input
                            type="text"
                            value={formData.meta_title}
                            onChange={(e) => setFormData({ ...formData, meta_title: e.target.value })}
                            className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                            maxLength={70}
                        />
                        <p className="mt-1 text-xs text-slate-500">{formData.meta_title?.length || 0}/70</p>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-300 mb-2">
                            Meta Description (max 160 chars)
                        </label>
                        <textarea
                            value={formData.meta_description}
                            onChange={(e) => setFormData({ ...formData, meta_description: e.target.value })}
                            className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                            rows={3}
                            maxLength={160}
                        />
                        <p className="mt-1 text-xs text-slate-500">{formData.meta_description?.length || 0}/160</p>
                    </div>
                </div>
            </div>

            {/* Status */}
            <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">
                    Status
                </label>
                <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                    className="w-full px-4 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                >
                    <option value="draft">Draft</option>
                    <option value="published">Published</option>
                    <option value="archived">Archived</option>
                </select>
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-4">
                <button
                    type="submit"
                    disabled={saveMutation.isPending}
                    className="px-6 py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-slate-600 text-white rounded-lg font-medium transition"
                >
                    {saveMutation.isPending ? 'Saving...' : (pageId ? 'Update Page' : 'Create Page')}
                </button>

                {pageId && (
                    <button
                        type="button"
                        onClick={handlePreview}
                        className="px-6 py-2 bg-slate-600 hover:bg-slate-500 text-white rounded-lg font-medium transition"
                    >
                        Preview
                    </button>
                )}

                {onCancel && (
                    <button
                        type="button"
                        onClick={onCancel}
                        className="px-6 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg font-medium transition"
                    >
                        Cancel
                    </button>
                )}
            </div>

            {/* Error Display */}
            {saveMutation.isError && (
                <div className="p-4 bg-red-900/20 border border-red-700 rounded-lg text-red-400">
                    Error: {saveMutation.error.message}
                </div>
            )}

            {/* Success Display */}
            {saveMutation.isSuccess && (
                <div className="p-4 bg-green-900/20 border border-green-700 rounded-lg text-green-400">
                    ✅ Page saved successfully!
                </div>
            )}
        </form>
    );
}
