import { useState } from 'react';
import { Bell, BellOff, Check, CheckCheck, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Pagination } from '@/components/ui/Pagination';
import { PageContainer, PageTitle } from '@/components/ui/Typography';
import { useAdminNotifications, useMarkNotificationRead, useMarkAllNotificationsRead } from '../core/_hooks';
import { AdminNotification } from '../core/_models';
import { formatDateTime } from '@/utils/formatters';
import { ReportSkeleton } from '@/components/common/ReportSkeleton';
import { toast } from 'react-hot-toast';

const AdminNotificationsListPage = () => {
  const [filters, setFilters] = useState({ offset: 0, limit: 20 });
  const [filterType, setFilterType] = useState<'all' | 'unread'>('all');

  const { data, isLoading, error } = useAdminNotifications(filters);
  const { mutate: markRead, isPending: isMarkingRead } = useMarkNotificationRead();
  const { mutate: markAllRead, isPending: isMarkingAllRead } = useMarkAllNotificationsRead();

  const notifications = data?.notifications || [];
  const unreadCount = data?.unread_count || 0;
  const totalPages = Math.ceil((data?.notifications?.length || 0) / filters.limit);

  const filteredNotifications = filterType === 'unread' 
    ? notifications.filter(n => !n.is_read)
    : notifications;

  const handlePageChange = (page: number) => {
    setFilters(prev => ({
      ...prev,
      offset: (page - 1) * prev.limit,
    }));
  };

  const handleMarkAsRead = (notificationId: number) => {
    markRead(notificationId, {
      onSuccess: () => {
        toast.success('نوتیفیکیشن به عنوان خوانده شده علامت‌گذاری شد');
      },
      onError: () => {
        toast.error('خطا در علامت‌گذاری نوتیفیکیشن');
      },
    });
  };

  const handleMarkAllAsRead = () => {
    markAllRead(undefined, {
      onSuccess: () => {
        toast.success('همه نوتیفیکیشن‌ها به عنوان خوانده شده علامت‌گذاری شدند');
      },
      onError: () => {
        toast.error('خطا در علامت‌گذاری نوتیفیکیشن‌ها');
      },
    });
  };

  const getNotificationIcon = (notification: AdminNotification) => {
    if (notification.metadata?.alert_type === 'failed_order_creation') {
      return <AlertCircle className="h-5 w-5 text-red-600" />;
    }
    return <Bell className="h-5 w-5 text-blue-600" />;
  };

  if (isLoading) {
    return (
      <PageContainer>
        <ReportSkeleton />
      </PageContainer>
    );
  }

  if (error) {
    return (
      <PageContainer>
        <div className="text-center py-12">
          <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
          <p className="text-gray-500 dark:text-gray-400">خطا در بارگذاری نوتیفیکیشن‌ها</p>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <div className="flex items-center justify-between mb-6">
        <PageTitle>اعلانات ادمین</PageTitle>
        <div className="flex items-center gap-4">
          {unreadCount > 0 && (
            <Button
              variant="secondary"
              onClick={handleMarkAllAsRead}
              disabled={isMarkingAllRead}
            >
              <CheckCheck className="h-4 w-4 ml-2" />
              همه را خوانده شده علامت بزن
            </Button>
          )}
        </div>
      </div>

      <div className="mb-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
          <div className="flex items-center">
            <Bell className="h-8 w-8 text-blue-600" />
            <div className="mr-3">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">کل اعلانات</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{notifications.length}</p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
          <div className="flex items-center">
            <BellOff className="h-8 w-8 text-red-600" />
            <div className="mr-3">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">خوانده نشده</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{unreadCount}</p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
          <div className="flex items-center">
            <Check className="h-8 w-8 text-green-600" />
            <div className="mr-3">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">خوانده شده</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                {notifications.length - unreadCount}
              </p>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            لیست اعلانات
          </h3>
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value as 'all' | 'unread')}
            className="input min-w-[150px]"
          >
            <option value="all">همه اعلانات</option>
            <option value="unread">خوانده نشده</option>
          </select>
        </div>

        <div className="p-6">
          <div className="space-y-4">
            {filteredNotifications.length === 0 ? (
              <div className="text-center py-12">
                <Bell className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500 dark:text-gray-400">هیچ اعلانی یافت نشد</p>
              </div>
            ) : (
              filteredNotifications.map((notification) => (
                <div
                  key={notification.id}
                  className={`p-4 border-r-4 ${
                    notification.is_read
                      ? 'border-r-gray-300 bg-gray-50 dark:bg-gray-700'
                      : 'border-r-blue-500 bg-white dark:bg-gray-800'
                  } border border-gray-200 dark:border-gray-600 rounded-lg shadow-sm hover:shadow-md transition-shadow`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start space-x-3 flex-1">
                      <div className="flex-shrink-0 mt-1">
                        {getNotificationIcon(notification)}
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2">
                          <h3
                            className={`text-sm font-medium ${
                              notification.is_read
                                ? 'text-gray-600 dark:text-gray-400'
                                : 'text-gray-900 dark:text-gray-100'
                            }`}
                          >
                            {notification.title}
                          </h3>
                          {!notification.is_read && (
                            <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                          )}
                        </div>

                        <p
                          className={`mt-1 text-sm whitespace-pre-line ${
                            notification.is_read
                              ? 'text-gray-500 dark:text-gray-500'
                              : 'text-gray-700 dark:text-gray-300'
                          }`}
                        >
                          {notification.message}
                        </p>

                        {notification.metadata && Object.keys(notification.metadata).length > 0 && (
                          <div className="mt-2 text-xs text-gray-500 dark:text-gray-500">
                            {notification.metadata.invoice_id && (
                              <span className="ml-4">شماره فاکتور: {notification.metadata.invoice_id}</span>
                            )}
                            {notification.metadata.payment_id && (
                              <span className="ml-4">شماره پرداخت: {notification.metadata.payment_id}</span>
                            )}
                          </div>
                        )}

                        <div className="mt-2 text-xs text-gray-500 dark:text-gray-500">
                          {formatDateTime(notification.created_at)}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center space-x-2 mr-4">
                      {!notification.is_read && (
                        <Button
                          size="sm"
                          variant="secondary"
                          onClick={() => handleMarkAsRead(notification.id)}
                          disabled={isMarkingRead}
                        >
                          <Check className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          {totalPages > 1 && (
            <div className="mt-6">
              <Pagination
                currentPage={Math.floor(filters.offset / filters.limit) + 1}
                totalPages={totalPages}
                onPageChange={handlePageChange}
                itemsPerPage={filters.limit}
                totalItems={notifications.length}
              />
            </div>
          )}
        </div>
      </div>
    </PageContainer>
  );
};

export default AdminNotificationsListPage;
