import React, { useState, useEffect, useMemo, useRef, useLayoutEffect } from 'react';
import { useApi, apiFetch } from '../hooks/useApi';

function planRowId(plan) {
    const n = Number(plan.id);
    return Number.isFinite(n) ? n : plan.id;
}

export default function Subscriptions() {
    const { data: plans, loading, refetch } = useApi('plans');
    const displayPlans = useMemo(
        () => (plans && plans.length > 0 ? plans : []),
        [plans]
    );
    const [selectedIds, setSelectedIds] = useState([]);
    const [bulkAction, setBulkAction] = useState('');
    const [bulkWorking, setBulkWorking] = useState(false);
    const selectAllRef = useRef(null);

    const [isFormOpen, setIsFormOpen] = useState(false);
    const [editingId, setEditingId] = useState(null);
    const [saving, setSaving] = useState(false);

    const [form, setForm] = useState({
        id: null,
        title: '',
        description: '',
        price: '',
        interval: 'month',
        signup_fee: '',
        trial_period: '',
        media: '',
        tags: ''
    });
    const [featureImageLoadError, setFeatureImageLoadError] = useState(false);
    const [previewPlan, setPreviewPlan] = useState(null);

    useEffect(() => {
        setFeatureImageLoadError(false);
    }, [form.media]);

    const openCreate = () => {
        setEditingId(null);
        setForm({ id: null, title: '', description: '', price: '', interval: 'month', signup_fee: '', trial_period: '', media: '', tags: '' });
        setIsFormOpen(true);
    };

    const openEdit = (plan) => {
        const normalizedId = planRowId(plan);
        setEditingId(normalizedId);
        setForm({
            id: normalizedId,
            title: plan.title || '',
            description: plan.description || '',
            price: plan.price || '',
            interval: plan.interval || 'month',
            signup_fee: plan.signup_fee || '',
            trial_period: plan.trial_period || '',
            media: plan.media || '',
            tags: plan.tags || ''
        });
        setIsFormOpen(true);
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            const targetId = form.id ?? editingId;
            if (targetId) {
                await apiFetch(`plans/${targetId}`, {
                    method: 'POST',
                    body: JSON.stringify({ ...form, id: targetId })
                });
            } else {
                await apiFetch('plans', {
                    method: 'POST',
                    body: JSON.stringify(form)
                });
            }
            setIsFormOpen(false);
            refetch();
        } catch {
            alert('Failed to save subscription plan');
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('Are you sure you want to delete this subscription plan?')) return;
        try {
            await apiFetch(`plans/${id}`, { method: 'DELETE' });
            refetch();
        } catch {
            alert('Failed to delete plan');
        }
    };

    useEffect(() => {
        setSelectedIds((prev) =>
            prev.filter((id) => displayPlans.some((p) => planRowId(p) === id))
        );
    }, [displayPlans]);

    const allSelected =
        displayPlans.length > 0 && selectedIds.length === displayPlans.length;
    const someSelected = selectedIds.length > 0 && !allSelected;

    useLayoutEffect(() => {
        const el = selectAllRef.current;
        if (el) {
            el.indeterminate = someSelected;
        }
    }, [someSelected, allSelected]);

    const toggleSelectAll = () => {
        if (allSelected) {
            setSelectedIds([]);
        } else {
            setSelectedIds(displayPlans.map((p) => planRowId(p)));
        }
    };

    const toggleRow = (id) => {
        setSelectedIds((prev) =>
            prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
        );
    };

    const handleBulkApply = async () => {
        if (!bulkAction) {
            return;
        }
        if (bulkAction === 'delete') {
            if (selectedIds.length === 0) {
                window.alert('Select at least one plan.');
                return;
            }
            const n = selectedIds.length;
            if (
                !window.confirm(
                    `Delete ${n} plan${n === 1 ? '' : 's'}? This cannot be undone.`
                )
            ) {
                return;
            }
            setBulkWorking(true);
            try {
                await Promise.all(
                    selectedIds.map((id) =>
                        apiFetch(`plans/${id}`, { method: 'DELETE' })
                    )
                );
                setSelectedIds([]);
                setBulkAction('');
                refetch();
            } catch {
                window.alert('Failed to delete one or more plans.');
            } finally {
                setBulkWorking(false);
            }
        }
    };

    const openMediaLibrary = (e) => {
        e.preventDefault();

        if (!window.wp || typeof window.wp.media !== 'function') {
            window.alert(
                'WordPress Media Library is not available. Ensure wp_enqueue_media() runs on this screen.'
            );
            return;
        }

        const pickUnderscore = () => {
            const stashed = window.__invizoWpUnderscore;
            if (
                stashed &&
                typeof stashed.defaults === 'function' &&
                typeof stashed.isArray === 'function'
            ) {
                return stashed;
            }
            const cur = window._;
            if (
                cur &&
                typeof cur.defaults === 'function' &&
                typeof cur.isArray === 'function'
            ) {
                return cur;
            }
            return null;
        };

        const wpUnderscore = pickUnderscore();
        if (!wpUnderscore) {
            window.alert(
                'WordPress Underscore could not be loaded for the media library. Try a hard refresh or check for a plugin that removes or replaces Underscore on admin pages.'
            );
            return;
        }

        const previousUnderscore = window._;
        window._ = wpUnderscore;

        let frame;
        let restored = false;
        const restoreUnderscore = () => {
            if (restored) {
                return;
            }
            restored = true;
            window._ = previousUnderscore;
        };

        try {
            frame = window.wp.media({
                title: 'Feature image',
                button: { text: 'Use this image' },
                multiple: false,
                library: { type: 'image' },
            });
        } catch {
            restoreUnderscore();
            window.alert('Could not open the media library.');
            return;
        }

        frame.on('close', restoreUnderscore);

        frame.on('select', () => {
            const attachment = frame.state().get('selection').first().toJSON();
            const url =
                attachment.sizes?.medium?.url ||
                attachment.sizes?.large?.url ||
                attachment.sizes?.full?.url ||
                attachment.url;
            setForm((prev) => ({ ...prev, media: url || '' }));
        });

        frame.open();
    };

    const clearFeatureImage = () => {
        setForm((prev) => ({ ...prev, media: '' }));
    };

    return (
        <div className="p-6">
            <div className="flex justify-between items-center mb-8">
                <h1 className="text-3xl font-normal text-[#2c3338]">Subscription Plans</h1>
                {!isFormOpen && (
                    <button onClick={openCreate} className="px-4 py-1.5 bg-[#f6f7f7] border border-[#2271b1] text-[#2271b1] rounded text-sm font-medium hover:bg-[#f0f0f1] transition-all cursor-pointer">
                        Add New Subscription
                    </button>
                )}
            </div>

            {isFormOpen ? (
                <div className="bg-white border rounded shadow-sm p-6 max-w-4xl animate-in fade-in slide-in-from-top-2 duration-300">
                    <div className="flex justify-between items-center mb-6 border-b pb-4">
                        <h2 className="text-xl font-medium">
                            {editingId ? `Edit Subscription Plan #${editingId}` : 'Create New Subscription Plan'}
                        </h2>
                        <button onClick={() => setIsFormOpen(false)} className="text-gray-400 hover:text-gray-600 cursor-pointer">
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>
                    </div>

                    <form onSubmit={handleSave} className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-[#2c3338] mb-1">Plan Title</label>
                                <input required value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="e.g. Monthly Pro" />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-[#2c3338] mb-1">Description</label>
                                <textarea rows="4" value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="Enter plan highlights..." />
                            </div>

                            <div className="flex gap-4">
                                <div className="flex-1">
                                    <label className="block text-sm font-medium text-[#2c3338] mb-1">Price ($)</label>
                                    <input required type="number" step="0.01" value={form.price} onChange={e => setForm({ ...form, price: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="19.99" />
                                </div>
                                <div className="flex-1">
                                    <label className="block text-sm font-medium text-[#2c3338] mb-1">Interval</label>
                                    <select value={form.interval} onChange={e => setForm({ ...form, interval: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none bg-white">
                                        <option value="day">Daily</option>
                                        <option value="week">Weekly</option>
                                        <option value="month">Monthly</option>
                                        <option value="year">Yearly</option>
                                    </select>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-[#2c3338] mb-1">Signup Fee ($)</label>
                                    <input type="number" step="0.01" value={form.signup_fee} onChange={e => setForm({ ...form, signup_fee: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="0.00" />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-[#2c3338] mb-1">Free Trial (days)</label>
                                    <input type="number" value={form.trial_period} onChange={e => setForm({ ...form, trial_period: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="e.g. 7" />
                                </div>
                            </div>
                        </div>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-[#2c3338] mb-1">Feature image</label>
                                <p className="text-xs text-[#646970] mb-2">
                                    Plan cover image. Use the media library or paste a direct image URL below.
                                </p>
                                <div className="border border-[#c3c4c7] rounded bg-[#f6f7f7] p-4 flex flex-col sm:flex-row gap-4">
                                    <div
                                        className="w-full sm:w-52 shrink-0 aspect-4/3 bg-white border border-[#dcdcde] rounded flex items-center justify-center overflow-hidden"
                                        aria-label="Feature image preview"
                                    >
                                        {form.media && !featureImageLoadError ? (
                                            <img
                                                src={form.media}
                                                alt=""
                                                className="max-h-44 w-full object-contain"
                                                onError={() => setFeatureImageLoadError(true)}
                                            />
                                        ) : form.media && featureImageLoadError ? (
                                            <span className="text-xs text-[#b32d2e] px-2 text-center">
                                                Could not load image. Check the URL.
                                            </span>
                                        ) : (
                                            <span className="text-xs text-[#646970] px-2 text-center">No image selected</span>
                                        )}
                                    </div>
                                    <div className="flex flex-col gap-2 min-w-0 flex-1">
                                        <div className="flex flex-wrap gap-2">
                                            <button
                                                type="button"
                                                onClick={openMediaLibrary}
                                                className="px-3 py-1.5 bg-[#2271b1] text-white border border-[#2271b1] rounded text-sm font-medium hover:bg-[#135e96] cursor-pointer"
                                            >
                                                {form.media ? 'Replace image' : 'Select image'}
                                            </button>
                                            {form.media ? (
                                                <button
                                                    type="button"
                                                    onClick={clearFeatureImage}
                                                    className="px-3 py-1.5 bg-white border border-[#b32d2e] text-[#b32d2e] rounded text-sm font-medium hover:bg-[#fcf0f1] cursor-pointer"
                                                >
                                                    Remove image
                                                </button>
                                            ) : null}
                                        </div>
                                        <div>
                                            <label className="block text-xs font-medium text-[#50575e] mb-1">Image URL (optional)</label>
                                            <input
                                                value={form.media}
                                                onChange={(e) => setForm({ ...form, media: e.target.value })}
                                                className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none bg-white"
                                                placeholder="/wp-content/uploads/plan-cover.jpg"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-[#2c3338] mb-1">Tags (Comma separated)</label>
                                <input value={form.tags} onChange={e => setForm({ ...form, tags: e.target.value })} className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none" placeholder="featured, popular, limited" />
                            </div>

                            <div className="pt-6 flex justify-end gap-3">
                                <button type="button" onClick={() => setIsFormOpen(false)} className="px-6 py-2 border border-gray-300 rounded text-sm font-medium hover:bg-gray-50 cursor-pointer transition-all">Cancel</button>
                                <button type="submit" disabled={saving} className="px-6 py-2 bg-[#2271b1] text-white rounded text-sm font-bold hover:bg-[#135e96] cursor-pointer shadow-md transition-all">
                                    {saving ? 'Saving...' : (editingId ? 'Update Subscription' : 'Create Subscription')}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            ) : (
                <div className="bg-white border text-sm rounded shadow-sm mb-6">
                    <div className="p-3 border-b flex justify-between items-center bg-[#f8f9fa] text-[#50575e]">
                        <div className="flex gap-2 items-center">
                            <select
                                value={bulkAction}
                                onChange={(e) => setBulkAction(e.target.value)}
                                className="invizo-bulk-select border border-[#8c8f94] rounded text-xs px-2 py-1 bg-white outline-none min-w-40 max-w-56 shadow-sm relative z-20"
                                style={{ color: '#1d2327', backgroundColor: '#fff' }}
                            >
                                <option value="" style={{ color: '#1d2327', backgroundColor: '#fff' }}>
                                    Bulk actions
                                </option>
                                <option value="delete" style={{ color: '#1d2327', backgroundColor: '#fff' }}>
                                    Delete
                                </option>
                            </select>
                            <button
                                type="button"
                                onClick={handleBulkApply}
                                disabled={bulkWorking || !bulkAction}
                                className="border border-blue-400 text-blue-700 bg-blue-50/80 rounded text-xs px-4 py-1.5 font-bold hover:bg-blue-100 transition-all shadow-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                {bulkWorking ? 'Applying…' : 'Apply'}
                            </button>
                        </div>
                        <div className="flex gap-4 items-center">
                            <span className="text-xs">{displayPlans.length} items</span>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="w-full text-left" style={{ fontSize: '13px' }}>
                            <thead className="bg-[#f8f9fa] border-b text-[#2c3338]">
                                <tr>
                                    <th className="p-2 py-3 pl-4 font-medium w-10">
                                        <input
                                            ref={selectAllRef}
                                            type="checkbox"
                                            className="rounded-sm border-gray-400"
                                            checked={allSelected}
                                            onChange={toggleSelectAll}
                                            disabled={displayPlans.length === 0 || loading}
                                        />
                                    </th>
                                    <th className="p-2 py-3 font-medium w-16">Media</th>
                                    <th className="p-2 py-3 font-medium text-[#2271b1]">Title</th>
                                    <th className="p-2 py-3 font-medium">Recurring Price</th>
                                    <th className="p-2 py-3 font-medium">Interval</th>
                                    <th className="p-2 py-3 font-medium">Tags</th>
                                    <th className="p-2 py-3 font-medium w-24">ID</th>
                                </tr>
                            </thead>
                            <tbody className="text-[#3c434a]">
                                {loading ? (
                                    <tr><td colSpan="7" className="p-4 text-center text-gray-500">Loading templates...</td></tr>
                                ) : displayPlans.length === 0 ? (
                                    <tr><td colSpan="7" className="p-4 text-center text-gray-500">No subscription plans found. Add one to get started.</td></tr>
                                ) : displayPlans.map((plan, idx) => {
                                    const rowId = planRowId(plan);
                                    return (
                                    <tr key={rowId} className={`group hover:bg-[#f6f7f7] border-b border-gray-50 last:border-0 ${idx % 2 === 0 ? 'bg-white' : 'bg-[#fcfcfc]'}`}>
                                        <td className="p-2 py-4 pl-4 align-top">
                                            <input
                                                type="checkbox"
                                                className="rounded-sm border-gray-400"
                                                checked={selectedIds.includes(rowId)}
                                                onChange={() => toggleRow(rowId)}
                                            />
                                        </td>
                                        <td className="p-2 py-4 align-top">
                                            {plan.media ? (
                                                <img src={plan.media} className="w-10 h-10 object-cover rounded border" />
                                            ) : (
                                                <div className="w-10 h-10 bg-gray-100 rounded border flex items-center justify-center text-[10px] text-gray-400">No Image</div>
                                            )}
                                        </td>
                                        <td className="p-2 py-4 align-top relative">
                                            <div className="font-bold text-[#2271b1] cursor-pointer hover:underline mb-1" onClick={() => openEdit(plan)}>{plan.title}</div>
                                            <div className="text-[11px] text-gray-500 line-clamp-1 max-w-xs">{plan.description || 'No description provided.'}</div>

                                            <div className="flex flex-wrap gap-x-2 gap-y-1 items-center mt-2 opacity-0 group-hover:opacity-100 transition-opacity text-[11px]">
                                                <button type="button" onClick={() => openEdit(plan)} className="text-[#2271b1] hover:text-[#135e96] cursor-pointer">Edit</button>
                                                <span className="text-gray-300">|</span>
                                                {plan.preview_url && String(plan.preview_url).trim() !== '' ? (
                                                    <a
                                                        href={plan.preview_url}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="text-[#2271b1] hover:text-[#135e96] cursor-pointer"
                                                    >
                                                        View
                                                    </a>
                                                ) : (
                                                    <button
                                                        type="button"
                                                        onClick={() => setPreviewPlan(plan)}
                                                        className="text-[#2271b1] hover:text-[#135e96] cursor-pointer"
                                                    >
                                                        View
                                                    </button>
                                                )}
                                                <span className="text-gray-300">|</span>
                                                <button type="button" onClick={() => handleDelete(rowId)} className="text-[#b32d2e] hover:text-[#8a2424] cursor-pointer">Trash</button>
                                            </div>
                                        </td>
                                        <td className="p-2 py-4 align-top font-medium">${plan.price}</td>
                                        <td className="p-2 py-4 align-top capitalize text-gray-600">{plan.interval}ly</td>
                                        <td className="p-2 py-4 align-top">
                                            <div className="flex flex-wrap gap-1">
                                                {plan.tags ? plan.tags.split(',').map((tag, i) => (
                                                    <span key={i} className="px-1.5 py-0.5 bg-gray-100 border text-gray-600 rounded text-[10px] uppercase font-bold tracking-tight">{tag.trim()}</span>
                                                )) : <span className="text-gray-300">-</span>}
                                            </div>
                                        </td>
                                        <td className="p-2 py-4 align-top font-mono text-gray-400">{plan.id}</td>
                                    </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {previewPlan ? (
                <div
                    className="fixed inset-0 z-100050 flex items-center justify-center p-4 bg-black/40"
                    role="dialog"
                    aria-modal="true"
                    aria-labelledby="invizo-plan-preview-title"
                    onClick={() => setPreviewPlan(null)}
                >
                    <div
                        className="bg-white rounded border border-[#c3c4c7] shadow-lg max-w-lg w-full max-h-[90vh] overflow-y-auto text-sm"
                        onClick={(ev) => ev.stopPropagation()}
                    >
                        <div className="flex justify-between items-center border-b border-[#dcdcde] px-4 py-3 bg-[#f6f7f7]">
                            <h2 id="invizo-plan-preview-title" className="text-base font-semibold text-[#1d2327] m-0">
                                Plan preview
                            </h2>
                            <button
                                type="button"
                                onClick={() => setPreviewPlan(null)}
                                className="text-[#50575e] hover:text-[#1d2327] cursor-pointer p-1 rounded"
                                aria-label="Close preview"
                            >
                                <svg className="w-5 h-5" 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 className="p-4 space-y-3 text-[#3c434a]">
                            {previewPlan.media ? (
                                <div className="rounded border border-[#dcdcde] bg-[#f6f7f7] p-2 flex justify-center">
                                    <img
                                        src={previewPlan.media}
                                        alt=""
                                        className="max-h-48 w-full object-contain"
                                    />
                                </div>
                            ) : null}
                            <div>
                                <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Title</div>
                                <div className="text-[#1d2327] font-semibold">{previewPlan.title || '—'}</div>
                            </div>
                            <div>
                                <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Description</div>
                                <div className="whitespace-pre-wrap">{previewPlan.description || 'No description.'}</div>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Price</div>
                                    <div>${previewPlan.price ?? '—'}</div>
                                </div>
                                <div>
                                    <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Interval</div>
                                    <div className="capitalize">{previewPlan.interval ? `${previewPlan.interval}ly` : '—'}</div>
                                </div>
                                <div>
                                    <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Signup fee</div>
                                    <div>{previewPlan.signup_fee !== undefined && previewPlan.signup_fee !== '' ? `$${previewPlan.signup_fee}` : '—'}</div>
                                </div>
                                <div>
                                    <div className="text-xs font-medium text-[#646970] uppercase tracking-wide">Trial (days)</div>
                                    <div>{previewPlan.trial_period !== undefined && previewPlan.trial_period !== '' ? previewPlan.trial_period : '—'}</div>
                                </div>
                            </div>
                            {previewPlan.tags ? (
                                <div>
                                    <div className="text-xs font-medium text-[#646970] uppercase tracking-wide mb-1">Tags</div>
                                    <div className="flex flex-wrap gap-1">
                                        {previewPlan.tags.split(',').map((tag, i) => (
                                            <span
                                                key={i}
                                                className="px-1.5 py-0.5 bg-gray-100 border text-gray-600 rounded text-[10px] uppercase font-bold"
                                            >
                                                {tag.trim()}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            ) : null}
                            <div className="text-xs text-[#646970]">Plan ID: {previewPlan.id}</div>
                        </div>
                        <div className="border-t border-[#dcdcde] px-4 py-3 bg-[#f6f7f7] flex justify-end">
                            <button
                                type="button"
                                onClick={() => setPreviewPlan(null)}
                                className="px-4 py-1.5 bg-[#2271b1] text-white rounded text-sm font-medium hover:bg-[#135e96] cursor-pointer"
                            >
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            ) : null}
        </div>
    );
}
