import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Bell, 
  CheckCircle, 
  AlertCircle, 
  Info, 
  Package, 
  MessageSquare,
  Check
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";

interface Notification {
  id: string;
  type: 'order' | 'system' | 'message' | 'update';
  title: string;
  content: string;
  time: string;
  read: boolean;
  priority: 'high' | 'medium' | 'low';
}

const mockNotifications: Notification[] = [
  {
    id: '1',
    type: 'order',
    title: '订单发货通知',
    content: '您的订单 #12345 已发货，预计3-5个工作日内送达。您可以通过快递单号进行物流跟踪。',
    time: '2分钟前',
    read: false,
    priority: 'high'
  },
  {
    id: '2',
    type: 'message',
    title: 'AI助手回复',
    content: '关于您咨询的产品问题，我已为您准备了详细解答，请查看聊天记录获取更多信息。',
    time: '10分钟前',
    read: false,
    priority: 'medium'
  },
  {
    id: '3',
    type: 'system',
    title: '系统维护通知',
    content: '系统将于今晚23:00-01:00进行维护升级，期间服务可能短暂中断，请您提前做好准备。',
    time: '1小时前',
    read: true,
    priority: 'medium'
  },
  {
    id: '4',
    type: 'update',
    title: '功能更新',
    content: '智能客服新增语音交互功能，体验更加便捷。您现在可以通过语音与AI助手进行交流。',
    time: '2小时前',
    read: true,
    priority: 'low'
  },
  {
    id: '5',
    type: 'order',
    title: '订单确认',
    content: '您的订单 #12344 已确认，我们正在为您准备商品，预计24小时内发货。',
    time: '1天前',
    read: true,
    priority: 'medium'
  },
  {
    id: '6',
    type: 'system',
    title: '账户安全提醒',
    content: '检测到您的账户在新设备上登录，如非本人操作请及时修改密码。',
    time: '2天前',
    read: true,
    priority: 'high'
  },
  {
    id: '7',
    type: 'message',
    title: '客服消息',
    content: '您的售后申请已受理，客服专员将在2个工作日内联系您处理相关问题。',
    time: '3天前',
    read: true,
    priority: 'medium'
  },
  {
    id: '8',
    type: 'update',
    title: '新功能上线',
    content: '平台新增在线支付功能，支持多种支付方式，让您的购物体验更加便捷。',
    time: '1周前',
    read: true,
    priority: 'low'
  }
];

const getNotificationIcon = (type: string) => {
  switch (type) {
    case 'order':
      return <Package className="h-5 w-5 text-primary" />;
    case 'system':
      return <AlertCircle className="h-5 w-5 text-warning" />;
    case 'message':
      return <MessageSquare className="h-5 w-5 text-ai" />;
    case 'update':
      return <Info className="h-5 w-5 text-info" />;
    default:
      return <Bell className="h-5 w-5 text-muted-foreground" />;
  }
};

const getPriorityColor = (priority: string) => {
  switch (priority) {
    case 'high':
      return 'bg-destructive text-destructive-foreground';
    case 'medium':
      return 'bg-warning text-warning-foreground';
    case 'low':
      return 'bg-info text-info-foreground';
    default:
      return 'bg-muted text-muted-foreground';
  }
};

interface NotificationDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function NotificationDialog({ open, onOpenChange }: NotificationDialogProps) {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState("all");
  const [notifications, setNotifications] = useState(mockNotifications);

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

  const getFilteredNotifications = (tab: string) => {
    if (tab === "all") return notifications;
    if (tab === "unread") return notifications.filter(n => !n.read);
    return notifications.filter(n => n.type === tab);
  };

  const markAllAsRead = () => {
    setNotifications(notifications.map(n => ({ ...n, read: true })));
    toast({
      title: "操作成功",
      description: "所有通知已标记为已读"
    });
  };

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

  const renderNotificationList = (filteredNotifications: Notification[]) => (
    <div className="space-y-3">
      {filteredNotifications.length > 0 ? (
        filteredNotifications.map((notification) => (
          <div
            key={notification.id}
            className={cn(
              "flex items-start space-x-4 p-4 rounded-lg border transition-all duration-200 hover:shadow-md cursor-pointer",
              notification.read 
                ? "bg-muted/30 border-border/50" 
                : "bg-card border-border shadow-sm"
            )}
            onClick={() => markAsRead(notification.id)}
          >
            <div className="flex-shrink-0 mt-1">
              {getNotificationIcon(notification.type)}
            </div>
            
            <div className="flex-1 min-w-0">
              <div className="flex items-start justify-between mb-2">
                <div className="flex items-center space-x-2">
                  <h4 className={cn(
                    "text-base font-medium",
                    !notification.read && "text-foreground"
                  )}>
                    {notification.title}
                  </h4>
                  {!notification.read && (
                    <span className="h-2 w-2 bg-primary rounded-full flex-shrink-0" />
                  )}
                </div>
                <Badge className={getPriorityColor(notification.priority)}>
                  {notification.priority === 'high' && '高优先级'}
                  {notification.priority === 'medium' && '中优先级'}
                  {notification.priority === 'low' && '低优先级'}
                </Badge>
              </div>
              
              <p className="text-sm text-muted-foreground mb-2 line-clamp-2">
                {notification.content}
              </p>
              
              <div className="flex items-center justify-between mt-3">
                <span className="text-xs text-muted-foreground">{notification.time}</span>
                {notification.read && (
                  <div className="flex items-center text-xs text-muted-foreground">
                    <Check className="h-3 w-3 mr-1" />
                    <span>已读</span>
                  </div>
                )}
              </div>
            </div>
          </div>
        ))
      ) : (
        <Card className="border-dashed">
          <CardContent className="py-12 text-center">
            <Bell className="h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-50" />
            <p className="text-muted-foreground">暂无通知消息</p>
          </CardContent>
        </Card>
      )}
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] p-0 overflow-hidden" aria-describedby="notification-description">
        <DialogHeader className="p-6 pb-4 border-b">
          <p id="notification-description" className="sr-only">管理您的通知消息</p>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <Bell className="h-6 w-6 text-primary" />
              <div>
                <DialogTitle className="text-2xl">通知中心</DialogTitle>
                <p className="text-sm text-muted-foreground mt-1">查看和管理您的所有通知消息</p>
              </div>
              {unreadCount > 0 && (
                <Badge variant="destructive" className="h-6 text-sm">
                  {unreadCount} 条未读
                </Badge>
              )}
            </div>
            {unreadCount > 0 && (
              <Button 
                onClick={markAllAsRead}
                variant="outline" 
                size="sm"
                className="flex items-center space-x-2"
              >
                <CheckCircle className="h-4 w-4" />
                <span>标记全部为已读</span>
              </Button>
            )}
          </div>
        </DialogHeader>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
            <TabsList className="grid w-full grid-cols-6 text-xs sm:text-sm">
              <TabsTrigger value="all">全部</TabsTrigger>
              <TabsTrigger value="unread">未读</TabsTrigger>
              <TabsTrigger value="order">订单</TabsTrigger>
              <TabsTrigger value="message">消息</TabsTrigger>
              <TabsTrigger value="system">系统</TabsTrigger>
              <TabsTrigger value="update">更新</TabsTrigger>
            </TabsList>

            <TabsContent value="all" className="mt-4">
              {renderNotificationList(getFilteredNotifications("all"))}
            </TabsContent>

            <TabsContent value="unread" className="mt-4">
              {renderNotificationList(getFilteredNotifications("unread"))}
            </TabsContent>

            <TabsContent value="order" className="mt-4">
              {renderNotificationList(getFilteredNotifications("order"))}
            </TabsContent>

            <TabsContent value="message" className="mt-4">
              {renderNotificationList(getFilteredNotifications("message"))}
            </TabsContent>

            <TabsContent value="system" className="mt-4">
              {renderNotificationList(getFilteredNotifications("system"))}
            </TabsContent>

            <TabsContent value="update" className="mt-4">
              {renderNotificationList(getFilteredNotifications("update"))}
            </TabsContent>
          </Tabs>
        </div>
      </DialogContent>
    </Dialog>
  );
}
