import { useState, useEffect } from 'react';
import { Tractor, Map, Clipboard, Package, Brain, Droplets, Settings, Bell, User, X, CheckCircle, LogOut, UserCircle, Sprout, Sun, Moon, RefreshCw } from 'lucide-react';
import { useAuth } from './auth/AuthContext';
import { useTheme } from './ThemeProvider';
import { toast } from 'sonner@2.0.3';
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';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';

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

interface NavigationProps {
  activeTab: string;
  onTabChange: (tab: string) => void;
  onMessageClick?: () => void;
  onProfileClick?: () => void;
}

export function Navigation({ activeTab, onTabChange, onMessageClick, onProfileClick }: NavigationProps) {
  const { authState, logout } = useAuth();
  const { theme, toggleTheme } = useTheme();
  const [showMessages, setShowMessages] = useState(false);
  const [showMessageDetail, setShowMessageDetail] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [showUserMenu, setShowUserMenu] = useState(false);
  
  // 角色切换状态
  const [currentRole, setCurrentRole] = useState<string>('');
  const [availableRoles, setAvailableRoles] = useState<{id: string, name: string}[]>([]);
  const [userRealName, setUserRealName] = useState<string>('');
  
  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',
    },
  ]);

  const menuItems = [
    { id: 'machinery', label: '智能农机管理系统', icon: Tractor },
    { id: 'field', label: '地块信息管理系统', icon: Map },
    { id: 'operation', label: '农事操作管理系统', icon: Clipboard },
    { id: 'asset', label: '农业资产管理系统', icon: Package },
    { id: 'ai-model', label: 'AI作物模型精准决策系统', icon: Brain },
    { id: 'irrigation', label: '水肥一体化控制系统', icon: Droplets },
    { id: 'config', label: '中心配置管理系统', icon: Settings },
  ];

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

  // 初始化角色数据和用户姓名
  useEffect(() => {
    if (authState.user) {
      try {
        const profileData = localStorage.getItem('smart_agriculture_user_profile');
        if (profileData) {
          const profile = JSON.parse(profileData);
          
          // 设置用户真实姓名
          setUserRealName(profile.realName || profile.name || authState.user.realName || authState.user.username || '用户');
          
          if (profile.roleIds && profile.roleNames && Array.isArray(profile.roleIds)) {
            const roles = profile.roleIds.map((id: string, index: number) => ({
              id,
              name: profile.roleNames[index] || id
            }));
            setAvailableRoles(roles);
            
            // 获取当前角色
            const savedRole = localStorage.getItem('smart_agriculture_current_role');
            setCurrentRole(savedRole || roles[0]?.id || '');
          }
        } else {
          // 如果没有profile数据，使用authState中的数据
          setUserRealName(authState.user.realName || authState.user.username || '用户');
        }
      } catch (error) {
        console.error('加载角色数据失败:', error);
        setUserRealName(authState.user?.realName || authState.user?.username || '用户');
      }
    }
  }, [authState.user]);

  // 角色切换处理
  const handleRoleChange = (roleId: string) => {
    setCurrentRole(roleId);
    localStorage.setItem('smart_agriculture_current_role', roleId);
    const roleName = availableRoles.find(r => r.id === roleId)?.name || '';
    toast.success(`已切换到「${roleName}」角色`);
  };

  const handleProfileClick = () => {
    if (onProfileClick) {
      onProfileClick();
    }
  };

  const handleViewAllMessages = () => {
    setShowMessages(false);
    // 切换到消息中心
    onTabChange('config');
    if (onMessageClick) {
      onMessageClick();
    }
  };

  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 getMessageTypeColor = (type?: string) => {
    switch (type) {
      case 'warning':
        return 'text-warning';
      case 'error':
        return 'text-error';
      case 'success':
        return 'text-success';
      default:
        return 'text-info';
    }
  };

  const getMessageTypeBg = (type?: string) => {
    switch (type) {
      case 'warning':
        return 'bg-warning-muted';
      case 'error':
        return 'bg-error-muted';
      case 'success':
        return 'bg-success-muted';
      default:
        return 'bg-info-muted';
    }
  };

  return (
    <nav className="bg-background border-b border-border shadow-sm transition-colors">
      <div className="flex items-center justify-between px-6 py-4 gap-6">
        {/* 系统标题 */}
        <div className="flex items-center gap-3 flex-shrink-0">
          <div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center transition-colors">
            <Sprout className="w-6 h-6 text-primary-foreground" />
          </div>
          <div>
            <h1 className="text-primary transition-colors" style={{ color: 'var(--primary)' }}>智慧农业生产管理系统</h1>
            <p className="text-xs text-muted-foreground">Smart Agriculture Management System</p>
          </div>
        </div>

        {/* 子系统菜单 */}
        <div className="flex items-center gap-1 overflow-x-auto flex-1">
          {menuItems.map((item) => {
            const Icon = item.icon;
            const isActive = activeTab === item.id;
            return (
              <button
                key={item.id}
                onClick={() => onTabChange(item.id)}
                className={`
                  flex items-center gap-2 px-4 py-2 whitespace-nowrap transition-colors relative rounded-lg
                  ${isActive 
                    ? 'text-primary bg-primary/10' 
                    : 'text-foreground hover:text-primary hover:bg-primary/5'
                  }
                `}
              >
                <Icon className="w-4 h-4" />
                <span className="text-sm">{item.label}</span>
                {isActive && (
                  <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
                )}
              </button>
            );
          })}
        </div>

        {/* 右侧操作区 */}
        <div className="flex items-center gap-2 flex-shrink-0">
          {/* 主题切换 */}
          <Button 
            variant="ghost" 
            size="icon"
            onClick={toggleTheme}
            title={theme === 'light' ? '切换到深色模式' : '切换到浅色模式'}
            className="transition-colors"
          >
            {theme === 'light' ? (
              <Moon className="w-5 h-5" />
            ) : (
              <Sun className="w-5 h-5" />
            )}
          </Button>

          {/* 消息通知 */}
          <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-error text-error-foreground 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-accent 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-muted' : 'bg-info'}`} />
                        <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>

          {/* 个人中心 */}
          <Popover open={showUserMenu} onOpenChange={setShowUserMenu}>
            <PopoverTrigger asChild>
              <Button variant="ghost" className="gap-2">
                <User className="w-5 h-5" />
                <span className="text-sm hidden md:inline">{authState.user?.username || 'admin'}</span>
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-72 p-0" align="end">
              <div className="p-4 border-b bg-gradient-to-r from-primary/10 to-accent">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-primary rounded-full flex items-center justify-center text-primary-foreground">
                    <UserCircle className="w-6 h-6" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h4 className="mb-1 truncate">{userRealName}</h4>
                    <p className="text-xs text-muted-foreground truncate">
                      {availableRoles.find(r => r.id === currentRole)?.name || (authState.user?.role === 'admin' ? '系统管理员' : '普通用户')}
                    </p>
                  </div>
                </div>
              </div>
              <div className="p-2">
                {/* 角色切换器 */}
                {availableRoles.length > 1 && (
                  <div className="p-3 border-b">
                    <div className="flex items-center justify-between mb-2">
                      <label className="text-xs text-muted-foreground uppercase tracking-wider">当前角色</label>
                      <RefreshCw className="w-3 h-3 text-muted-foreground" />
                    </div>
                    <Select value={currentRole} onValueChange={handleRoleChange}>
                      <SelectTrigger className="h-9">
                        <SelectValue placeholder="选择角色" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableRoles.map((role) => (
                          <SelectItem key={role.id} value={role.id}>
                            <div className="flex items-center gap-2">
                              <div className={`w-2 h-2 rounded-full ${role.id === currentRole ? 'bg-success' : 'bg-muted'}`} />
                              <span>{role.name}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground mt-2">
                      切换角色后将使用对应的权限访问系统
                    </p>
                  </div>
                )}
                
                {/* 用户信息 */}
                <div className="p-3 space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">用户名:</span>
                    <span>{authState.user?.username}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">手机号:</span>
                    <span>{authState.user?.phone}</span>
                  </div>
                  {authState.user?.enterpriseName && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">所属企业:</span>
                      <span className="truncate max-w-[140px]" title={authState.user?.enterpriseName}>
                        {authState.user?.enterpriseName}
                      </span>
                    </div>
                  )}
                  {authState.user?.department && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">部门:</span>
                      <span>{authState.user?.department}</span>
                    </div>
                  )}
                  {authState.user?.lastLoginTime && (
                    <div className="flex justify-between text-xs">
                      <span className="text-muted-foreground">上次登录:</span>
                      <span className="text-muted-foreground">{authState.user?.lastLoginTime}</span>
                    </div>
                  )}
                </div>
                <div className="border-t pt-2 mt-2">
                  <Button
                    variant="ghost"
                    className="w-full justify-start text-sm"
                    onClick={() => {
                      setShowUserMenu(false);
                      handleProfileClick();
                    }}
                  >
                    <User className="w-4 h-4 mr-2" />
                    个人中心
                  </Button>
                  <Button
                    variant="ghost"
                    className="w-full justify-start text-sm text-destructive hover:text-destructive hover:bg-destructive/10"
                    onClick={() => {
                      setShowUserMenu(false);
                      logout();
                      toast.success('已安全退出登录');
                    }}
                  >
                    <LogOut className="w-4 h-4 mr-2" />
                    退出登录
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </div>
      </div>

      {/* 消息详情对话框 */}
      <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>
    </nav>
  );
}
