import React, { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDiscountCodes, useDeleteDiscountCode, useDiscountReports } from '../core/_hooks';
import { DiscountCode } from '../core/_models';
import { Table } from "@/components/ui/Table";
import { TableColumn } from "@/types";
import { BadgePercent, Plus, Ticket, Hash, DollarSign, Users } from 'lucide-react';
import { PageContainer } from "@/components/ui/Typography";
import { PageHeader } from "@/components/layout/PageHeader";
import { FiltersSection } from "@/components/common/FiltersSection";
import { EmptyState } from "@/components/common/EmptyState";
import { DeleteConfirmModal } from "@/components/common/DeleteConfirmModal";
import { ActionButtons } from "@/components/common/ActionButtons";
import { StatusBadge } from "@/components/ui/StatusBadge";
import { Modal } from "@/components/ui/Modal";
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
import { formatCurrency, formatDate, formatDateTime } from "@/utils/formatters";
import { formatWithThousands } from "@/utils/numberUtils";

const DiscountCodesListPage = () => {
    const navigate = useNavigate();
    const [deleteId, setDeleteId] = useState<string | null>(null);
    const [filters, setFilters] = useState({ code: '' });
    const [selectedDiscount, setSelectedDiscount] = useState<DiscountCode | null>(null);
    const [isUsageModalOpen, setIsUsageModalOpen] = useState(false);

    const { data: discountCodes, isLoading, error } = useDiscountCodes(filters);
    const { mutate: deleteDiscount, isPending: isDeleting } = useDeleteDiscountCode();
    const summaryFilters = useMemo(
        () => ({
            view_mode: 'simple' as const,
            limit: 1,
            offset: 0,
        }),
        []
    );
    const { data: discountReport, isLoading: isReportLoading, error: reportError } =
        useDiscountReports(summaryFilters);
    const usageFilters = useMemo(() => {
        if (!selectedDiscount) return undefined;
        return {
            view_mode: 'simple' as const,
            discount_id: selectedDiscount.id,
            include_unused: true,
            limit: 1,
            offset: 0,
        };
    }, [selectedDiscount]);
    const {
        data: usageReport,
        isLoading: isUsageLoading,
        error: usageError,
    } = useDiscountReports(usageFilters, isUsageModalOpen && !!selectedDiscount);
    const selectedUsage = usageReport?.usages?.[0];

    const handleCreate = useCallback(() => navigate('/discount-codes/create'), [navigate]);
    const handleEdit = useCallback((id: number) => navigate(`/discount-codes/${id}/edit`), [navigate]);

    const handleDeleteConfirm = () => {
        if (deleteId) {
            deleteDiscount(deleteId, { onSuccess: () => setDeleteId(null) });
        }
    };

    const handleOpenUsageModal = useCallback((discount: DiscountCode) => {
        setSelectedDiscount(discount);
        setIsUsageModalOpen(true);
    }, []);

    const handleCloseUsageModal = () => {
        setIsUsageModalOpen(false);
        setSelectedDiscount(null);
    };

    const columns: TableColumn[] = useMemo(() => [
        { key: 'code', label: 'کد', sortable: true },
        { key: 'name', label: 'نام', sortable: true },
        {
            key: 'value',
            label: 'مقدار',
            render: (_val, row: any) => row.type === 'percentage' ? `${row.value}%` : `${row.value} تومان`
        },
        {
            key: 'application_level',
            label: 'سطح',
            render: (_val, row: any) => row.application_level === 'invoice' ? 'کل سبد' : row.application_level === 'category' ? 'دسته‌بندی' : row.application_level === 'product' ? 'محصول' : 'ارسال'
        },
        {
            key: 'status',
            label: 'وضعیت',
            render: (val: string) => <StatusBadge status={val} type="discount" />
        },
        {
            key: 'period',
            label: 'بازه زمانی',
            render: (_val, row: any) => (
                <span>
                    {row.valid_from ? formatDate(row.valid_from) : '-'} تا {row.valid_to ? formatDate(row.valid_to) : '-'}
                </span>
            )
        },
        {
            key: 'actions',
            label: 'عملیات',
            render: (_val, row: any) => (
                <ActionButtons
                    onView={() => handleOpenUsageModal(row as DiscountCode)}
                    viewTitle="آمار استفاده"
                    onEdit={() => handleEdit(row.id)}
                    onDelete={() => setDeleteId(row.id.toString())}
                />
            )
        }
    ], [handleEdit, handleOpenUsageModal]);

    if (error) {
        return (
            <div className="p-6">
                <div className="text-center py-12">
                    <p className="text-red-600 dark:text-red-400">خطا در بارگذاری کدهای تخفیف</p>
                </div>
            </div>
        );
    }

    const createButton = (
                <button
                    onClick={handleCreate}
                    className="flex items-center justify-center w-12 h-12 bg-primary-600 hover:bg-primary-700 rounded-full transition-colors duration-200 text-white shadow-lg hover:shadow-xl"
                    title="کد تخفیف جدید"
                    data-testid="create-discount-button"
                >
                    <Plus className="h-5 w-5" />
                </button>
    );

    return (
        <PageContainer>
            <div className="space-y-6">
                <PageHeader
                    title="مدیریت کدهای تخفیف"
                    subtitle="ایجاد و مدیریت کدهای تخفیف"
                    icon={BadgePercent}
                    actions={createButton}
                />

                <FiltersSection isLoading={isLoading} columns={3}>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">کد</label>
                        <input
                            type="text"
                            placeholder="جستجو بر اساس کد..."
                            value={filters.code}
                            onChange={(e) => setFilters((prev) => ({ ...prev, code: e.target.value }))}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        />
                    </div>
                </FiltersSection>

                {isReportLoading ? (
                    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                        <LoadingSpinner size="sm" text="در حال بارگذاری آمار..." />
                    </div>
                ) : reportError ? (
                    <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                        <p className="text-red-600 dark:text-red-400">خطا در دریافت آمار تخفیف</p>
                    </div>
                ) : discountReport?.summary ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                                    <Hash className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600 dark:text-gray-400">کل استفاده‌ها</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatWithThousands(discountReport.summary.total_usages)}
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                                    <DollarSign className="h-5 w-5 text-green-600 dark:text-green-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600 dark:text-gray-400">مجموع تخفیف داده شده</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatCurrency(discountReport.summary.total_discount_given)}
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                                    <Users className="h-5 w-5 text-purple-600 dark:text-purple-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600 dark:text-gray-400">کاربران یونیک</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatWithThousands(discountReport.summary.unique_users)}
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-lg">
                                    <Hash className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600 dark:text-gray-400">کدهای یونیک</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatWithThousands(discountReport.summary.unique_codes)}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                ) : null}

            {isLoading ? (
                <Table columns={columns} data={Array.isArray(discountCodes) ? (discountCodes as any[]) : []} loading={true} />
            ) : !discountCodes || discountCodes.length === 0 ? (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                        <EmptyState
                            icon={Ticket}
                            title="هیچ کد تخفیفی یافت نشد"
                            description="برای شروع یک کد تخفیف ایجاد کنید"
                            actionLabel={
                                <>
                            <Plus className="h-4 w-4 ml-2" />
                            ایجاد کد تخفیف
                                </>
                            }
                            onAction={handleCreate}
                        />
                </div>
            ) : (
                <Table columns={columns} data={discountCodes as any[]} />
            )}

                <Modal
                    isOpen={isUsageModalOpen}
                    onClose={handleCloseUsageModal}
                    title={`آمار استفاده - ${selectedDiscount?.code || ''}`}
                    size="lg"
                >
                    {isUsageLoading ? (
                        <LoadingSpinner size="sm" text="در حال بارگذاری آمار..." />
                    ) : usageError ? (
                        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                            <p className="text-red-600 dark:text-red-400">خطا در دریافت آمار استفاده</p>
                        </div>
                    ) : selectedUsage ? (
                        <div className="space-y-4">
                            <div className="bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                <p className="text-sm text-gray-600 dark:text-gray-400">نام کد تخفیف</p>
                                <p className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                                    {selectedDiscount?.name || '-'}
                                </p>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                    <p className="text-sm text-gray-600 dark:text-gray-400">تعداد استفاده</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatWithThousands(selectedUsage.usage_count)}
                                    </p>
                                </div>
                                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                    <p className="text-sm text-gray-600 dark:text-gray-400">مجموع تخفیف</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatCurrency(selectedUsage.total_amount)}
                                    </p>
                                </div>
                                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                    <p className="text-sm text-gray-600 dark:text-gray-400">کاربران یونیک</p>
                                    <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                        {formatWithThousands(selectedUsage.unique_users)}
                                    </p>
                                </div>
                                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                    <p className="text-sm text-gray-600 dark:text-gray-400">اولین استفاده</p>
                                    <p className="text-base font-medium text-gray-900 dark:text-gray-100">
                                        {selectedUsage.first_used_at ? formatDateTime(selectedUsage.first_used_at) : '-'}
                                    </p>
                                </div>
                                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                    <p className="text-sm text-gray-600 dark:text-gray-400">آخرین استفاده</p>
                                    <p className="text-base font-medium text-gray-900 dark:text-gray-100">
                                        {selectedUsage.last_used_at ? formatDateTime(selectedUsage.last_used_at) : '-'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700 rounded-lg p-6 text-center">
                            <p className="text-gray-600 dark:text-gray-400">هیچ استفاده‌ای ثبت نشده است</p>
                        </div>
                    )}
                </Modal>

                <DeleteConfirmModal
                    isOpen={!!deleteId}
                    onClose={() => setDeleteId(null)}
                    onConfirm={handleDeleteConfirm}
                    title="حذف کد تخفیف"
                    message="آیا از حذف این کد تخفیف اطمینان دارید؟ این عمل قابل بازگشت نیست."
                    isLoading={isDeleting}
                />
                    </div>
        </PageContainer>
    );
};

export default DiscountCodesListPage;



