import React, { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDiscountCodes, useDeleteDiscountCode } from '../core/_hooks';
import { DiscountCode } from '../core/_models';
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { Table } from "@/components/ui/Table";
import { TableColumn } from "@/types";
import { Percent, BadgePercent, Trash2, Edit3, Plus, Ticket } from 'lucide-react';

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) => (
                <span className={`px-2 py-1 rounded-full text-xs ${val === 'active' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'}`}>
                    {val === 'active' ? 'فعال' : 'غیرفعال'}
                </span>
            )
        },
        {
            key: 'period',
            label: 'بازه زمانی',
            render: (_val, row: any) => (
                <span>
                    {row.valid_from ? new Date(row.valid_from).toLocaleDateString('fa-IR') : '-'} تا {row.valid_to ? new Date(row.valid_to).toLocaleDateString('fa-IR') : '-'}
                </span>
            )
        },
        {
            key: 'actions',
            label: 'عملیات',
            render: (_val, row: any) => (
                <div className="flex items-center gap-2">
                    <button
                        onClick={() => handleEdit(row.id)}
                        className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
                        title="ویرایش"
                    >
                        <Edit3 className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => setDeleteId(row.id.toString())}
                        className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                        title="حذف"
                    >
                        <Trash2 className="h-4 w-4" />
                    </button>
                </div>
            )
        }
    ], [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>
        );
    }

    return (
        <div className="p-6 space-y-6">
            <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                        <BadgePercent className="h-6 w-6" />
                        مدیریت کدهای تخفیف
                    </h1>
                    <p className="text-gray-600 dark:text-gray-400 mt-1">ایجاد و مدیریت کدهای تخفیف</p>
                </div>
                <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>
            </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="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <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>
                </div>
            </div>

            {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">
                    <div className="text-center py-12">
                        <Ticket className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-4" />
                        <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">هیچ کد تخفیفی یافت نشد</h3>
                        <p className="text-gray-600 dark:text-gray-400 mb-4">برای شروع یک کد تخفیف ایجاد کنید</p>
                        <Button onClick={handleCreate} className="flex items-center gap-2">
                            <Plus className="h-4 w-4 ml-2" />
                            ایجاد کد تخفیف
                        </Button>
                    </div>
                </div>
            ) : (
                <Table columns={columns} data={discountCodes as any[]} />
            )}

            <Modal isOpen={!!deleteId} onClose={() => setDeleteId(null)} title="حذف کد تخفیف">
                <div className="space-y-4">
                    <p className="text-gray-600 dark:text-gray-400">آیا از حذف این کد تخفیف اطمینان دارید؟ این عمل قابل بازگشت نیست.</p>
                    <div className="flex justify-end space-x-2 space-x-reverse">
                        <Button variant="secondary" onClick={() => setDeleteId(null)} disabled={isDeleting}>انصراف</Button>
                        <Button variant="danger" onClick={handleDeleteConfirm} loading={isDeleting}>حذف</Button>
                    </div>
                </div>
            </Modal>
        </div>
    );
};

export default DiscountCodesListPage;



