import React, { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDiscountCodes, useDeleteDiscountCode } from '../core/_hooks';
import { DiscountCode } from '../core/_models';
import { Table } from "@/components/ui/Table";
import { TableColumn } from "@/types";
import { BadgePercent, Plus, Ticket } 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 { formatDate } from "@/utils/formatters";

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

    const { data: discountCodes, isLoading, error } = useDiscountCodes(filters);
    const { mutate: deleteDiscount, isPending: isDeleting } = useDeleteDiscountCode();

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

    const handleDeleteConfirm = () => {
        if (deleteId) {
            deleteDiscount(deleteId, { onSuccess: () => setDeleteId(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
                    onEdit={() => handleEdit(row.id)}
                    onDelete={() => setDeleteId(row.id.toString())}
                />
            )
        }
    ], [navigate]);

    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>

                {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[]} />
                )}

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

export default DiscountCodesListPage;



