'use client';

import { useState } from 'react';
import { Bell, CheckCircle, X } from 'lucide-react';
import { toast } from 'sonner';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui/dialog';
import { ScrollArea } from './ui/scroll-area';

interface Message {
  id: string;
  title: string;
  content: string;
  fullContent?: string;
  time: string;
  read: boolean;
  type?: 'info' | 'warning' | 'success' | 'error';
}

interface MessageBellProps {
  onMessageClick?: () => void;
}

export function MessageBell({ onMessageClick }: MessageBellProps) {
  const [showMessages, setShowMessages] = useState(false);
  const [showMessageDetail, setShowMessageDetail] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      title: '系统维护通知',
      content: '系统将于今晚22:00进行维护升级',
      fullContent: '尊敬的用户：\n\n为了提升系统性能和用户体验，我们将于今晚22:00-23:00进行系统维护升级。\n\n维护期间，系统将暂时无法访问。维护完成后，系统将自动恢复正常。\n\n维护内容：\n1. 数据库性能优化\n2. 新功能上线\n3. 安全补丁更新\n\n给您带来的不便，敬请谅解。\n\n智慧农业管理系统',
      time: '10分钟前',
      read: false,
      type: 'info',
    },
    {
      id: '2',
      title: '作业任务提醒',
      content: '小麦播种作业任务已分配',
      fullContent: '您好！\n\n新的作业任务已分配给您：\n\n任务名称：小麦播种作业\n作业地块：1号地块（东区）\n作业面积：50亩\n计划时间：2024年10月15日 08:00\n负责驾驶员：张三\n使用设备：约翰迪尔拖拉机 JD-001\n\n请您及时查看任务详情，做好作业准备工作。如有问题，请及时联系调度中心。\n\n祝工作顺利！',
      time: '1小时前',
      read: false,
      type: 'success',
    },
    {
      id: '3',
      title: '设备预警',
      content: '拖拉机JD-001需要保养维护',
      fullContent: '设备预警通知\n\n设备名称：约翰迪尔拖拉机\n设备编号：JD-001\n当前工作时长：498小时\n\n该设备即将达到保养周期（500小时），建议尽快安排保养维护。\n\n保养项目：\n- 更换机油和机滤\n- 检查空气滤清器\n- 检查轮胎气压\n- 检查制动系统\n- 润滑各运动部件\n\n请及时联系维修部门预约保养时间。定期保养可以延长设备使用寿命，确保作业安全。\n\n设备管理中心',
      time: '2小时前',
      read: false,
      type: 'warning',
    },
    {
      id: '4',
      title: '消息日志通知',
      content: '新的消息日志记录已生成',
      fullContent: '消息日志通知\n\n系统已记录以下消息日志：\n\n1. 短信发送记录\n   - 接收人：张三\n   - 内容：任务分配通知\n   - 状态：发送成功\n   - 时间：2024-10-14 09:30:00\n\n2. 邮件发送记录\n   - 接收人：wangwu@example.com\n   - 内容：设备保养提醒\n   - 状态：发送成功\n   - 时间：2024-10-14 14:00:00\n\n3. 站内信记录\n   - 接收人：李四\n   - 内容：系统通知\n   - 状态：已读\n   - 时间：2024-10-14 15:30:00\n\n请查看消息日志页面了解详细信息。',
      time: '30分钟前',
      read: true,
      type: 'info',
    },
    {
      id: '5',
      title: '推送消息失败',
      content: '部分推送消息发送失败',
      fullContent: '推送消息失败通知\n\n以下推送消息发送失败：\n\n失败原因：设备离线\n- 接收人：赵六\n- 内容：天气预警通知\n- 失败时间：2024-10-14 16:00:00\n- 重试次数：3次\n\n处理建议：\n1. 检查设备网络连接\n2. 确认推送服务状态\n3. 联系用户确认设备状态\n\n系统将在24小时后自动重试发送。\n\n技术支持团队',
      time: '45分钟前',
      read: false,
      type: 'error',
    },
  ]);

  const unreadCount = messages.filter(m => !m.read).length;

  const handleMessageItemClick = (message: Message) => {
    // 标记消息为已读
    if (!message.read) {
      setMessages(messages.map(m =>
        m.id === message.id ? { ...m, read: true } : m
      ));
    }
    // 显示消息详情
    setSelectedMessage(message);
    setShowMessageDetail(true);
    setShowMessages(false);
  };

  const handleMarkAllRead = () => {
    setMessages(messages.map(m => ({ ...m, read: true })));
  };

  const handleViewAllMessages = () => {
    setShowMessages(false);
    if (onMessageClick) {
      onMessageClick();
    }
  };

  const getMessageTypeColor = (type?: string) => {
    switch (type) {
      case 'warning':
        return 'text-orange-600';
      case 'error':
        return 'text-red-600';
      case 'success':
        return 'text-green-600';
      default:
        return 'text-blue-600';
    }
  };

  const getMessageTypeBg = (type?: string) => {
    switch (type) {
      case 'warning':
        return 'bg-orange-50';
      case 'error':
        return 'bg-red-50';
      case 'success':
        return 'bg-green-50';
      default:
        return 'bg-blue-50';
    }
  };

  return (
    <>
      <Popover open={showMessages} onOpenChange={setShowMessages}>
        <PopoverTrigger asChild>
          <Button variant="ghost" size="icon" className="relative">
            <Bell
             className="w-5 h-5" />
            {unreadCount > 0 && (
              <Badge
                className="absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 bg-red-500 text-white text-xs"
              >
                {unreadCount}
              </Badge>
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-96 p-0" align="end">
          <div className="p-4 border-b">
            <div className="flex items-center justify-between">
              <h4>消息通知</h4>
              <div className="flex items-center gap-2">
                {unreadCount > 0 && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleMarkAllRead}
                    className="text-xs h-7"
                  >
                    <CheckCircle className="w-3 h-3 mr-1" />
                    全部已读
                  </Button>
                )}
                <Badge variant="outline">{unreadCount} 条未读</Badge>
              </div>
            </div>
          </div>
          <ScrollArea className="max-h-96">
            {messages.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                <Bell className="w-12 h-12 mx-auto mb-2 opacity-20" />
                <p className="text-sm">暂无消息</p>
              </div>
            ) : (
              messages.map((msg) => (
                <div
                  key={msg.id}
                  className="p-4 border-b hover:bg-gray-50 cursor-pointer transition-colors"
                  onClick={() => handleMessageItemClick(msg)}
                >
                  <div className="flex items-start gap-3">
                    <div className={`w-2 h-2 rounded-full mt-2 flex-shrink-0 ${msg.read ? 'bg-gray-300' : 'bg-blue-500'}`} />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <h5 className={`text-sm ${!msg.read ? '' : 'text-muted-foreground'}`}>
                          {msg.title}
                        </h5>
                        {msg.type && (
                          <Badge
                            variant="outline"
                            className={`text-xs ${getMessageTypeColor(msg.type)} border-current`}
                          >
                            {msg.type === 'warning' ? '预警' :
                             msg.type === 'error' ? '错误' :
                             msg.type === 'success' ? '成功' : '通知'}
                          </Badge>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{msg.content}</p>
                      <p className="text-xs text-muted-foreground mt-2">{msg.time}</p>
                    </div>
                  </div>
                </div>
              ))
            )}
          </ScrollArea>
          <div className="p-2 border-t">
            <Button
              variant="ghost"
              size="sm"
              className="w-full"
              onClick={handleViewAllMessages}
            >
              查看全部消息
            </Button>
          </div>
        </PopoverContent>
      </Popover>

      {/* 消息详情对话框 */}
      <Dialog open={showMessageDetail} onOpenChange={setShowMessageDetail}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center justify-between gap-4">
                <div className="flex items-center gap-2">
                  <Bell className={`w-5 h-5 ${selectedMessage ? getMessageTypeColor(selectedMessage.type) : ''}`} />
                  <span>{selectedMessage?.title}</span>
                </div>
                {selectedMessage?.type && (
                  <Badge
                    variant="outline"
                    className={`${getMessageTypeColor(selectedMessage.type)} border-current`}
                  >
                    {selectedMessage.type === 'warning' ? '⚠️ 预警' :
                     selectedMessage.type === 'error' ? '❌ 错误' :
                     selectedMessage.type === 'success' ? '✅ 成功' : 'ℹ️ 通知'}
                  </Badge>
                )}
              </div>
            </DialogTitle>
            <DialogDescription className="sr-only">
              查看消息详情
            </DialogDescription>
          </DialogHeader>
          {selectedMessage && (
            <div className="space-y-4">
              <div className={`p-4 rounded-lg ${getMessageTypeBg(selectedMessage.type)}`}>
                <div className="flex items-center justify-between mb-2">
                  <span className={`text-sm ${getMessageTypeColor(selectedMessage.type)}`}>
                    发送时间：{selectedMessage.time}
                  </span>
                </div>
              </div>
              <ScrollArea className="max-h-96">
                <div className="space-y-3">
                  <div className="whitespace-pre-wrap text-sm leading-relaxed">
                    {selectedMessage.fullContent || selectedMessage.content}
                  </div>
                </div>
              </ScrollArea>
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowMessageDetail(false)}
                >
                  关闭
                </Button>
                <Button
                  onClick={() => {
                    setShowMessageDetail(false);
                    handleViewAllMessages();
                  }}
                >
                  查看更多消息
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}