import { useState } from 'react';
import type { Route } from './+types/notifications';
import { Card, CardHeader, CardTitle, CardContent } from '~/components/ui/card/card';
import { Button } from '~/components/ui/button/button';
import { Badge } from '~/components/ui/badge/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs/tabs';
import { Switch } from '~/components/ui/switch/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '~/components/ui/select/select';
import { 
  Bell, 
  BellRing, 
  Check, 
  Trash2, 
  Filter,
  Settings,
  Clock,
  AlertCircle,
  CheckCircle,
  Info,
  Users
} from 'lucide-react';
import { mockNotifications, markAllNotificationsAsRead, type Notification } from '~/data/dashboard-stats';
import styles from './notifications.module.css';

export const meta: Route.MetaFunction = () => {
  return [{ title: 'Notifications' }];
};

export default function Notifications() {
  const [notifications, setNotifications] = useState(mockNotifications);
  const [filter, setFilter] = useState<'all' | 'unread'>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');

  const [notificationSettings, setNotificationSettings] = useState({
    subscriptionExpiry: true,
    paymentSuccess: true,
    serverIssues: true,
    newUsers: false,
    supportTickets: true,
    emailNotifications: true,
    pushNotifications: false,
    smsNotifications: false
  });

  const filteredNotifications = notifications.filter(n => {
    const matchesReadFilter = filter === 'all' || (filter === 'unread' && !n.read);
    const matchesTypeFilter = typeFilter === 'all' || n.type === typeFilter;
    return matchesReadFilter && matchesTypeFilter;
  });

  const unreadCount = notifications.filter(n => !n.read).length;

  const markAsRead = (id: string) => {
    setNotifications(prev => 
      prev.map(n => n.id === id ? { ...n, read: true } : n)
    );
  };

  const deleteNotification = (id: string) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  };

  const markAllAsRead = () => {
    setNotifications(prev => prev.map(n => ({ ...n, read: true })));
  };

  const getNotificationIcon = (type: Notification['type']) => {
    switch (type) {
      case 'subscription_expiring':
        return <Clock size={18} />;
      case 'payment_success':
        return <CheckCircle size={18} />;
      case 'server_issue':
        return <AlertCircle size={18} />;
      case 'new_user':
        return <Users size={18} />;
      case 'support_ticket':
        return <Info size={18} />;
      default:
        return <Bell size={18} />;
    }
  };

  const getPriorityColor = (priority: Notification['priority']) => {
    switch (priority) {
      case 'high':
        return 'destructive';
      case 'medium':
        return 'warning';
      case 'low':
        return 'secondary';
    }
  };

  const updateSetting = (key: keyof typeof notificationSettings, value: boolean) => {
    setNotificationSettings(prev => ({ ...prev, [key]: value }));
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div>
          <h1 className={styles.title}>
            <BellRing size={28} />
            اعلان‌ها
            {unreadCount > 0 && <Badge variant="destructive">{unreadCount}</Badge>}
          </h1>
          <p className={styles.subtitle}>مدیریت اعلان‌ها و تنظیمات</p>
        </div>
        <div className={styles.actions}>
          <Button variant="outline" onClick={markAllAsRead} disabled={unreadCount === 0}>
            <Check size={16} />
            علامت همه به عنوان خوانده شده
          </Button>
        </div>
      </div>

      <Tabs defaultValue="list" className={styles.tabs}>
        <TabsList>
          <TabsTrigger value="list">
            <Bell size={16} />
            لیست اعلان‌ها
          </TabsTrigger>
          <TabsTrigger value="settings">
            <Settings size={16} />
            تنظیمات
          </TabsTrigger>
        </TabsList>

        <TabsContent value="list">
          <Card>
            <CardHeader>
              <div className={styles.filterHeader}>
                <CardTitle>اعلان‌های اخیر</CardTitle>
                <div className={styles.filters}>
                  <Select value={filter} onValueChange={(value: any) => setFilter(value)}>
                    <SelectTrigger className={styles.filterSelect}>
                      <Filter size={14} />
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">همه</SelectItem>
                      <SelectItem value="unread">خوانده نشده</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select value={typeFilter} onValueChange={setTypeFilter}>
                    <SelectTrigger className={styles.filterSelect}>
                      <SelectValue placeholder="نوع" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">همه انواع</SelectItem>
                      <SelectItem value="subscription_expiring">اشتراک منقضی</SelectItem>
                      <SelectItem value="payment_success">پرداخت موفق</SelectItem>
                      <SelectItem value="server_issue">مشکل سرور</SelectItem>
                      <SelectItem value="new_user">کاربر جدید</SelectItem>
                      <SelectItem value="support_ticket">تیکت پشتیبانی</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {filteredNotifications.length === 0 ? (
                <div className={styles.emptyState}>
                  <Bell size={48} />
                  <p>اعلانی وجود ندارد</p>
                </div>
              ) : (
                <div className={styles.notificationList}>
                  {filteredNotifications.map(notification => (
                    <div 
                      key={notification.id} 
                      className={styles.notificationItem}
                      data-unread={!notification.read}
                      data-priority={notification.priority}
                    >
                      <div className={styles.notificationIcon}>
                        {getNotificationIcon(notification.type)}
                      </div>
                      <div className={styles.notificationContent}>
                        <div className={styles.notificationHeader}>
                          <h3 className={styles.notificationTitle}>{notification.title}</h3>
                          <div className={styles.notificationMeta}>
                            <Badge variant="outline">
                              {notification.priority === 'high' && 'فوری'}
                              {notification.priority === 'medium' && 'متوسط'}
                              {notification.priority === 'low' && 'عادی'}
                            </Badge>
                            <span className={styles.timestamp}>{notification.timestamp}</span>
                          </div>
                        </div>
                        <p className={styles.notificationMessage}>{notification.message}</p>
                        {notification.actionUrl && (
                          <a href={notification.actionUrl} className={styles.actionLink}>
                            مشاهده جزئیات →
                          </a>
                        )}
                      </div>
                      <div className={styles.notificationActions}>
                        {!notification.read && (
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={() => markAsRead(notification.id)}
                          >
                            <Check size={14} />
                          </Button>
                        )}
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => deleteNotification(notification.id)}
                        >
                          <Trash2 size={14} />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="settings">
          <div className={styles.settingsGrid}>
            <Card>
              <CardHeader>
                <CardTitle>نوع اعلان‌ها</CardTitle>
              </CardHeader>
              <CardContent>
                <div className={styles.settingsList}>
                  <div className={styles.settingItem}>
                    <div>
                      <h4>انقضای اشتراک</h4>
                      <p>هشدار وقتی اشتراک کاربران در حال اتمام است</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.subscriptionExpiry}
                      onCheckedChange={(checked) => updateSetting('subscriptionExpiry', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>پرداخت موفق</h4>
                      <p>اطلاع از پرداخت‌های موفق کاربران</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.paymentSuccess}
                      onCheckedChange={(checked) => updateSetting('paymentSuccess', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>مشکلات سرور</h4>
                      <p>هشدار فوری برای مشکلات سرورها</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.serverIssues}
                      onCheckedChange={(checked) => updateSetting('serverIssues', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>کاربران جدید</h4>
                      <p>اطلاع از ثبت‌نام کاربران جدید</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.newUsers}
                      onCheckedChange={(checked) => updateSetting('newUsers', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>تیکت‌های پشتیبانی</h4>
                      <p>اطلاع از تیکت‌های جدید</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.supportTickets}
                      onCheckedChange={(checked) => updateSetting('supportTickets', checked)}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>روش‌های اطلاع‌رسانی</CardTitle>
              </CardHeader>
              <CardContent>
                <div className={styles.settingsList}>
                  <div className={styles.settingItem}>
                    <div>
                      <h4>اعلان ایمیل</h4>
                      <p>دریافت اعلان‌ها از طریق ایمیل</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.emailNotifications}
                      onCheckedChange={(checked) => updateSetting('emailNotifications', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>Push Notification</h4>
                      <p>اعلان فوری در مرورگر</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.pushNotifications}
                      onCheckedChange={(checked) => updateSetting('pushNotifications', checked)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div>
                      <h4>پیامک</h4>
                      <p>ارسال پیامک برای اعلان‌های فوری</p>
                    </div>
                    <Switch 
                      checked={notificationSettings.smsNotifications}
                      onCheckedChange={(checked) => updateSetting('smsNotifications', checked)}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          <div className={styles.saveActions}>
            <Button>ذخیره تنظیمات</Button>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
