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

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

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

    useEffect(() => {
        setSelectedIds((prev) =>
            prev.filter((id) =>
                displaySubs.some((s) => subscriptionRowId(s) === id)
            )
        );
    }, [displaySubs]);

    const allSelected =
        displaySubs.length > 0 && selectedIds.length === displaySubs.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(displaySubs.map((s) => subscriptionRowId(s)));
        }
    };

    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 subscription.');
                return;
            }
            const n = selectedIds.length;
            if (
                !window.confirm(
                    `Delete ${n} subscription${n === 1 ? '' : 's'}? This cannot be undone.`
                )
            ) {
                return;
            }
            setBulkWorking(true);
            try {
                await Promise.all(
                    selectedIds.map((id) =>
                        apiFetch(`subscriptions/${id}`, { method: 'DELETE' })
                    )
                );
                setSelectedIds([]);
                setBulkAction('');
                refetch();
            } catch {
                window.alert('Failed to delete one or more subscriptions.');
            } finally {
                setBulkWorking(false);
            }
        }
    };

    return (
        <div className="p-6">
            <h1 className="text-3xl font-normal mb-8 text-[#2c3338]">Subscriptions</h1>

            <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-[10rem] max-w-[14rem] 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 hover:border-blue-500 transition-all shadow-[0_0_10px_rgba(59,130,246,0.3)] hover:shadow-[0_0_15px_rgba(59,130,246,0.6)] 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">{displaySubs.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={displaySubs.length === 0 || loading}
                                    />
                                </th>
                                <th className="p-2 py-3 font-medium text-[#2271b1]">Subscription ID</th>
                                <th className="p-2 py-3 font-medium text-[#2271b1]">Parent Order ID</th>
                                <th className="p-2 py-3 font-medium">Status</th>
                                <th className="p-2 py-3 font-medium">Product Name</th>
                                <th className="p-2 py-3 font-medium">Recurring Amount</th>
                                <th className="p-2 py-3 font-medium">User Name</th>
                                <th className="p-2 py-3 font-medium">Next Payment</th>
                                <th className="p-2 py-3 font-medium">Expiry Date</th>
                            </tr>
                        </thead>
                        <tbody className="text-[#3c434a]">
                            {loading ? (
                                <tr><td colSpan="9" className="p-4 text-center text-gray-500">Loading subscriptions...</td></tr>
                            ) : displaySubs.length === 0 ? (
                                <tr><td colSpan="9" className="p-4 text-center text-gray-500">No subscriptions found.</td></tr>
                            ) : displaySubs.map((sub, idx) => {
                                const rowId = subscriptionRowId(sub);
                                const hasExpiry =
                                    sub.expiry_date &&
                                    String(sub.expiry_date).trim() !== '' &&
                                    String(sub.expiry_date).trim() !== '---';
                                return (
                                <tr key={rowId} className={idx % 2 === 0 ? 'bg-white' : 'bg-[#f6f7f7]'}>
                                    <td className="p-2 py-4 pl-4">
                                        <input
                                            type="checkbox"
                                            className="rounded-sm border-gray-400"
                                            checked={selectedIds.includes(rowId)}
                                            onChange={() => toggleRow(rowId)}
                                        />
                                    </td>
                                    <td className="p-2 py-4 text-[#50575e]">{sub.id}</td>
                                    <td className="p-2 py-4 font-medium">
                                        {sub.order_url ? (
                                            <a href={sub.order_url} className="text-[#2271b1] hover:underline cursor-pointer">
                                                #{sub.order_id}
                                            </a>
                                        ) : (
                                            <span className="text-[#50575e]">{sub.order_id !== '---' ? '#' + sub.order_id : sub.order_id}</span>
                                        )}
                                    </td>
                                    <td className="p-2 py-4">
                                        <span className={`px-2 py-[2px] rounded text-[11px] font-semibold tracking-wide uppercase ${sub.status.toLowerCase() === 'active' ? 'bg-[#c6e1c6] text-[#2b542c]' :
                                            sub.status.toLowerCase() === 'expired' ? 'bg-[#eec5c5] text-[#843534]' :
                                                sub.status.toLowerCase() === 'pending' ? 'bg-[#d6d6d6] text-[#333333]' :
                                                    sub.status.toLowerCase() === 'cancelled' ? 'bg-[#f4d0a9] text-[#8a6d3b]' :
                                                        'bg-[#bce8f1] text-[#31708f]'
                                            }`}>{sub.status}</span>
                                    </td>
                                    <td className="p-2 py-4 text-[#50575e]">{sub.product_name}</td>
                                    <td className="p-2 py-4 text-[#50575e]">{sub.amount}</td>
                                    <td className="p-2 py-4 text-[#50575e]">
                                        {sub.user_name && String(sub.user_name).trim() !== ''
                                            ? sub.user_name
                                            : '—'}
                                    </td>
                                    <td className="p-2 py-4 text-[#50575e]">{sub.next_payment}</td>
                                    <td className="p-2 py-4 text-[#50575e]">{hasExpiry ? sub.expiry_date : '∞'}</td>
                                </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
}
