'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { purchasesApi } from '@/lib/api/purchases';
import { packagesApi } from '@/lib/api/packages';
import PageHeader from '@/components/admin/PageHeader';
import {
    Purchase,
    Paginated,
    PurchaseFilters,
    PAYMENT_GATEWAYS,
    PURCHASE_STATUSES,
    getGatewayLabel,
    getPurchaseStatusLabel,
} from '@/types/purchase';
import { PackageName } from '@/types/package';
import { formatPrice, formatDate, formatTime, getProductTypeLabel, getPurchaseFinalPrice } from '@/lib/utils';
import { MagnifyingGlassIcon, ArrowPathIcon } from '@heroicons/react/24/outline';

const statusBadgeClass = (status: number): string => {
    switch (status) {
        case 2:
            return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
        case 3:
            return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
        default:
            return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
    }
};

const emptyFilters: PurchaseFilters = {
    email: '',
    mobile: '',
    package_name: '',
    gateway: '',
    status: undefined,
};

export default function PurchasesPage() {
    const { token } = useAuth();
    const [packages, setPackages] = useState<PackageName[]>([]);
    const [filters, setFilters] = useState<PurchaseFilters>(emptyFilters);
    const [result, setResult] = useState<Paginated<Purchase> | null>(null);
    const [page, setPage] = useState(1);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const loadPurchases = useCallback(async (targetPage: number, activeFilters: PurchaseFilters) => {
        if (!token) return;
        setIsLoading(true);
        setError(null);
        try {
            const data = await purchasesApi.getPurchases(
                { ...activeFilters, page: targetPage, per_page: 30 },
                token
            );
            setResult(data);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در دریافت لیست خریدها');
        } finally {
            setIsLoading(false);
        }
    }, [token]);

    useEffect(() => {
        if (!token) return;
        packagesApi.getAllPackages(token).then(setPackages).catch(() => setPackages([]));
        loadPurchases(1, emptyFilters);
    }, [token, loadPurchases]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFilters((prev) => ({
            ...prev,
            [name]: name === 'status' ? (value === '' ? undefined : parseInt(value)) : value,
        }));
    };

    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        setPage(1);
        loadPurchases(1, filters);
    };

    const handleReset = () => {
        setFilters(emptyFilters);
        setPage(1);
        loadPurchases(1, emptyFilters);
    };

    const goToPage = (targetPage: number) => {
        setPage(targetPage);
        loadPurchases(targetPage, filters);
    };

    const inputClass =
        'block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm dark:bg-gray-800/80 transition-colors';
    const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';

    return (
        <div className="p-4 sm:p-8">
            <div className="max-w-7xl mx-auto">
                <PageHeader title="خریدهای اشتراک" />

                {/* Filters */}
                <form
                    onSubmit={handleSearch}
                    className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 sm:p-6 mb-6 shadow-sm"
                >
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
                        <div>
                            <label htmlFor="email" className={labelClass}>ایمیل</label>
                            <input type="text" id="email" name="email" value={filters.email || ''} onChange={handleInputChange} className={inputClass} placeholder="example@mail.com" dir="ltr" />
                        </div>
                        <div>
                            <label htmlFor="mobile" className={labelClass}>شماره موبایل</label>
                            <input type="text" id="mobile" name="mobile" value={filters.mobile || ''} onChange={handleInputChange} className={inputClass} placeholder="0912xxxxxxx" dir="ltr" />
                        </div>
                        <div>
                            <label htmlFor="package_name" className={labelClass}>پکیج</label>
                            <select id="package_name" name="package_name" value={filters.package_name || ''} onChange={handleInputChange} className={inputClass}>
                                <option value="">همه پکیج‌ها</option>
                                {packages.map((pkg) => (
                                    <option key={pkg.id} value={pkg.name || ''}>
                                        {pkg.title || pkg.name}
                                    </option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label htmlFor="gateway" className={labelClass}>منبع پرداخت</label>
                            <select id="gateway" name="gateway" value={filters.gateway || ''} onChange={handleInputChange} className={inputClass}>
                                <option value="">همه درگاه‌ها</option>
                                {Object.entries(PAYMENT_GATEWAYS).map(([key, g]) => (
                                    <option key={key} value={key}>{g.label}</option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label htmlFor="status" className={labelClass}>وضعیت</label>
                            <select id="status" name="status" value={filters.status ?? ''} onChange={handleInputChange} className={inputClass}>
                                <option value="">همه وضعیت‌ها</option>
                                {Object.entries(PURCHASE_STATUSES).map(([code, label]) => (
                                    <option key={code} value={code}>{label}</option>
                                ))}
                            </select>
                        </div>
                    </div>

                    <div className="flex flex-wrap items-center gap-3 mt-5">
                        <button
                            type="submit"
                            disabled={isLoading}
                            className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
                        >
                            <MagnifyingGlassIcon className="h-4 w-4" />
                            جستجو
                        </button>
                        <button
                            type="button"
                            onClick={handleReset}
                            disabled={isLoading}
                            className="inline-flex items-center gap-2 px-5 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm"
                        >
                            <ArrowPathIcon className="h-4 w-4" />
                            پاک کردن فیلترها
                        </button>
                    </div>
                </form>

                {error && (
                    <div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
                        <p className="text-sm text-red-700 dark:text-red-300">{error}</p>
                        <button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
                            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                )}

                {/* Results */}
                <div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
                    <div className="px-5 py-4 flex items-center justify-between border-b border-gray-200 dark:border-gray-800">
                        <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {result ? `${formatPrice(result.total)} خرید یافت شد` : 'در حال بارگذاری...'}
                        </h3>
                    </div>

                    {isLoading ? (
                        <div className="flex justify-center items-center py-16">
                            <div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
                        </div>
                    ) : !result || result.data.length === 0 ? (
                        <div className="text-center py-16">
                            <div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
                                <svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121 0 2.09-.773 2.34-1.872l1.836-8.046A1.125 1.125 0 0 0 18.054 3H5.106m2.394 11.25-1.5-6h13.5" />
                                </svg>
                            </div>
                            <p className="text-gray-500 dark:text-gray-400 text-sm">هیچ خریدی با این فیلترها یافت نشد</p>
                        </div>
                    ) : (
                        <>
                            {/* Mobile: stacked cards */}
                            <ul className="divide-y divide-gray-200 dark:divide-gray-800 md:hidden">
                                {result.data.map((purchase) => (
                                    <li key={purchase.id} className="px-5 py-4 space-y-2.5">
                                        <div className="flex items-start justify-between gap-3">
                                            <div className="min-w-0">
                                                <p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                                                    {purchase.product?.title || '—'}
                                                </p>
                                                <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
                                                    {purchase.product?.package_name?.title || purchase.product?.package_name?.name || '—'}
                                                    {purchase.product ? ` • ${getProductTypeLabel(purchase.product.type)}` : ''}
                                                </p>
                                            </div>
                                            <span className={`flex-shrink-0 px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${statusBadgeClass(purchase.status)}`}>
                                                {getPurchaseStatusLabel(purchase.status)}
                                            </span>
                                        </div>
                                        <div className="text-xs text-gray-500 dark:text-gray-400 space-y-0.5">
                                            <p className="font-medium text-gray-700 dark:text-gray-300">
                                                {purchase.user?.full_name?.trim() || 'بدون نام'}
                                            </p>
                                            {purchase.user?.email && (
                                                <p dir="ltr" className="text-right truncate">{purchase.user.email}</p>
                                            )}
                                            {purchase.user?.mobile && (
                                                <p dir="ltr" className="text-right truncate">{purchase.user.mobile}</p>
                                            )}
                                        </div>
                                        <div className="flex items-center justify-between gap-3 pt-2.5 border-t border-gray-100 dark:border-gray-800/60">
                                            <span className="text-sm font-bold text-gray-900 dark:text-gray-100">
                                                {formatPrice(getPurchaseFinalPrice(purchase))} تومان
                                            </span>
                                            <div className="flex flex-col items-end gap-1">
                                                <span className="px-2 py-0.5 text-[11px] font-medium rounded-md bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300">
                                                    {getGatewayLabel(purchase.gateway)}
                                                </span>
                                                <span className="text-[11px] text-gray-400 dark:text-gray-500">
                                                    {formatDate(purchase.created_at)} {formatTime(purchase.created_at)}
                                                </span>
                                            </div>
                                        </div>
                                    </li>
                                ))}
                            </ul>

                            {/* Desktop: table */}
                            <div className="hidden md:block overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
                                <thead className="bg-gray-50 dark:bg-gray-800/60">
                                    <tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                        <th className="px-4 py-3">کاربر</th>
                                        <th className="px-4 py-3">پکیج</th>
                                        <th className="px-4 py-3">محصول</th>
                                        <th className="px-4 py-3">قیمت نهایی</th>
                                        <th className="px-4 py-3">منبع پرداخت</th>
                                        <th className="px-4 py-3">وضعیت</th>
                                        <th className="px-4 py-3">تاریخ و ساعت</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                                    {result.data.map((purchase) => (
                                        <tr key={purchase.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
                                            <td className="px-4 py-3.5">
                                                <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                                    {purchase.user?.full_name?.trim() || 'بدون نام'}
                                                </div>
                                                <div className="text-xs text-gray-500 dark:text-gray-400" dir="ltr">
                                                    {purchase.user?.email || '—'}
                                                </div>
                                                <div className="text-xs text-gray-500 dark:text-gray-400" dir="ltr">
                                                    {purchase.user?.mobile || '—'}
                                                </div>
                                            </td>
                                            <td className="px-4 py-3.5 text-sm text-gray-700 dark:text-gray-300 whitespace-nowrap">
                                                {purchase.product?.package_name?.title || purchase.product?.package_name?.name || '—'}
                                            </td>
                                            <td className="px-4 py-3.5 whitespace-nowrap">
                                                <div className="text-sm text-gray-900 dark:text-gray-100">
                                                    {purchase.product?.title || '—'}
                                                </div>
                                                <div className="text-xs text-gray-500 dark:text-gray-400">
                                                    {purchase.product ? getProductTypeLabel(purchase.product.type) : ''}
                                                </div>
                                            </td>
                                            <td className="px-4 py-3.5 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap font-medium">
                                                {formatPrice(getPurchaseFinalPrice(purchase))} تومان
                                            </td>
                                            <td className="px-4 py-3.5 whitespace-nowrap">
                                                <span className="px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300">
                                                    {getGatewayLabel(purchase.gateway)}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3.5 whitespace-nowrap">
                                                <span className={`px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${statusBadgeClass(purchase.status)}`}>
                                                    {getPurchaseStatusLabel(purchase.status)}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
                                                {formatDate(purchase.created_at)} {formatTime(purchase.created_at)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                            </div>
                        </>
                    )}

                    {/* Pagination */}
                    {result && result.last_page > 1 && (
                        <div className="flex items-center justify-between px-5 py-3.5 border-t border-gray-200 dark:border-gray-800">
                            <button
                                onClick={() => goToPage(page - 1)}
                                disabled={page <= 1 || isLoading}
                                className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                            >
                                قبلی
                            </button>
                            <span className="text-sm text-gray-600 dark:text-gray-400">
                                صفحه {result.current_page} از {result.last_page}
                            </span>
                            <button
                                onClick={() => goToPage(page + 1)}
                                disabled={page >= result.last_page || isLoading}
                                className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                            >
                                بعدی
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
