'use client';

import React, { useState } from 'react';
import { MessageCircle, User, Settings, Home, Search, LogOut, Menu } from 'lucide-react';
import { useAuthStore } from '../../stores/auth-store';
import { ResponsiveLayout } from '../../features/shared/components/layout/responsive-layout';
import { MobileBottomNav, useBottomNav } from '../../features/shared/components/layout/mobile-layout';
import { Button } from '../../features/shared/components/ui/button';
import { Card } from '../../features/shared/components/ui/card';
import { useRouter } from 'next/navigation';

/**
 * EN: Dashboard Page - Main authenticated user interface
 * VI: Trang Dashboard - Giao diện chính cho người dùng đã xác thực
 *
 * Features:
 * - Responsive layout (desktop sidebar + mobile bottom nav)
 * - Quick actions and status overview
 * - Navigation to different sections
 * - User greeting and avatar
 */
export default function DashboardPage() {
  const { user, logout } = useAuthStore();
  const router = useRouter();
  const { activeItem, handleNavPress } = useBottomNav('home');
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  if (!user) {
    router.push('/auth/login');
    return null;
  }

  const handleLogout = async () => {
    await logout();
    router.push('/');
  };

  // Desktop Header
  const desktopHeader = (
    <div className="flex items-center justify-between w-full">
      <div className="flex items-center space-x-4">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
          className="p-2"
        >
          <Menu className="w-5 h-5" />
        </Button>
        <h1 className="text-xl font-semibold text-white">Dashboard</h1>
      </div>
      <div className="flex items-center space-x-4">
        <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
          <span className="text-blue-600 font-semibold text-sm">
            {user.email[0].toUpperCase()}
          </span>
        </div>
        <Button variant="ghost" size="sm" onClick={handleLogout}>
          <LogOut className="w-4 h-4 mr-2" />
          Logout
        </Button>
      </div>
    </div>
  );

  // Mobile Header
  const mobileHeader = (
    <div className="flex items-center justify-between w-full px-4">
      <h1 className="text-lg font-semibold text-white">Dashboard</h1>
      <div className="flex items-center space-x-2">
        <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
          <span className="text-blue-600 font-semibold text-sm">
            {user.email[0].toUpperCase()}
          </span>
        </div>
      </div>
    </div>
  );

  // Desktop Sidebar
  const desktopSidebar = (
    <div className="p-4">
      <div className="mb-8">
        <div className="flex items-center space-x-3 mb-6">
          <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
            <span className="text-blue-600 font-semibold">
              {user.email[0].toUpperCase()}
            </span>
          </div>
          {!sidebarCollapsed && (
            <div>
              <p className="font-medium text-gray-900">{user.email}</p>
              <p className="text-sm text-gray-500 capitalize">{user.role.toLowerCase()}</p>
            </div>
          )}
        </div>

        {!sidebarCollapsed && (
          <nav className="space-y-2">
            {[
              { id: 'home', label: 'Home', icon: Home },
              { id: 'chat', label: 'Chat', icon: MessageCircle },
              { id: 'search', label: 'Search', icon: Search },
              { id: 'profile', label: 'Profile', icon: User },
              { id: 'settings', label: 'Settings', icon: Settings },
            ].map((item) => {
              const Icon = item.icon;
              return (
                <button
                  key={item.id}
                  onClick={() => {
                    if (item.id === 'chat') router.push('/chat');
                    else if (item.id === 'profile') router.push('/profile');
                    else if (item.id === 'settings') router.push('/settings');
                  }}
                  className="w-full flex items-center space-x-3 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors"
                >
                  <Icon className="w-5 h-5 text-gray-600" />
                  <span className="text-gray-700">{item.label}</span>
                </button>
              );
            })}
          </nav>
        )}
      </div>

      {!sidebarCollapsed && (
        <div className="border-t pt-4">
          <Button
            variant="secondary"
            size="sm"
            onClick={handleLogout}
            className="w-full flex items-center justify-center"
          >
            <LogOut className="w-4 h-4 mr-2" />
            Logout
          </Button>
        </div>
      )}
    </div>
  );

  // Mobile Bottom Navigation Items
  const mobileNavItems = [
    {
      id: 'home',
      label: 'Home',
      icon: <Home className="w-6 h-6" />,
    },
    {
      id: 'search',
      label: 'Search',
      icon: <Search className="w-6 h-6" />,
    },
    {
      id: 'chat',
      label: 'Chat',
      icon: <MessageCircle className="w-6 h-6" />,
      badge: 2,
    },
    {
      id: 'profile',
      label: 'Profile',
      icon: <User className="w-6 h-6" />,
    },
    {
      id: 'settings',
      label: 'Settings',
      icon: <Settings className="w-6 h-6" />,
    },
  ];

  const handleMobileNavPress = (itemId: string) => {
    handleNavPress(itemId);
    if (itemId === 'chat') router.push('/chat');
    else if (itemId === 'profile') router.push('/profile');
    else if (itemId === 'settings') router.push('/settings');
  };

  // Dashboard Content
  const dashboardContent = (
    <div className="p-6 max-w-4xl mx-auto">
      {/* Welcome Section */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">
          Welcome back, {user.email.split('@')[0]}!
        </h2>
        <p className="text-gray-600">
          Here's what's happening with your account today.
        </p>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-3 bg-blue-100 rounded-lg">
              <MessageCircle className="w-6 h-6 text-blue-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Active Chats</p>
              <p className="text-2xl font-bold text-gray-900">3</p>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-3 bg-green-100 rounded-lg">
              <User className="w-6 h-6 text-green-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Profile Views</p>
              <p className="text-2xl font-bold text-gray-900">12</p>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-3 bg-purple-100 rounded-lg">
              <Settings className="w-6 h-6 text-purple-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Settings Updated</p>
              <p className="text-2xl font-bold text-gray-900">2</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <Card className="p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Quick Actions</h3>
          <div className="space-y-3">
            <Button
              onClick={() => router.push('/chat')}
              className="w-full flex items-center justify-start"
              variant="secondary"
            >
              <MessageCircle className="w-4 h-4 mr-3" />
              Start New Chat
            </Button>
            <Button
              onClick={() => router.push('/profile')}
              className="w-full flex items-center justify-start"
              variant="secondary"
            >
              <User className="w-4 h-4 mr-3" />
              Update Profile
            </Button>
            <Button
              onClick={() => router.push('/settings')}
              className="w-full flex items-center justify-start"
              variant="secondary"
            >
              <Settings className="w-4 h-4 mr-3" />
              Account Settings
            </Button>
          </div>
        </Card>

        <Card className="p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Recent Activity</h3>
          <div className="space-y-3">
            <div className="flex items-center space-x-3">
              <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
              <p className="text-sm text-gray-600">Started a new conversation</p>
              <span className="text-xs text-gray-400">2h ago</span>
            </div>
            <div className="flex items-center space-x-3">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <p className="text-sm text-gray-600">Updated profile information</p>
              <span className="text-xs text-gray-400">1d ago</span>
            </div>
            <div className="flex items-center space-x-3">
              <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
              <p className="text-sm text-gray-600">Changed notification settings</p>
              <span className="text-xs text-gray-400">3d ago</span>
            </div>
          </div>
        </Card>
      </div>

      {/* Account Status */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Account Status</h3>
        <div className="flex items-center justify-between">
          <div>
            <p className="font-medium text-gray-900">Account Active</p>
            <p className="text-sm text-gray-600">
              Your account is in good standing. Member since {new Date(user.createdAt).getFullYear()}.
            </p>
          </div>
          <div className={`px-3 py-1 rounded-full text-sm font-medium ${
            user.isActive
              ? 'bg-green-100 text-green-800'
              : 'bg-red-100 text-red-800'
          }`}>
            {user.isActive ? 'Active' : 'Inactive'}
          </div>
        </div>
      </Card>
    </div>
  );

  return (
    <ResponsiveLayout
      // Desktop props
      header={desktopHeader}
      sidebar={desktopSidebar}
      showSidebar={true}
      sidebarWidth={sidebarCollapsed ? 64 : 280}
      sidebarCollapsible={true}
      sidebarCollapsed={sidebarCollapsed}

      // Mobile props
      showBottomNav={true}
      bottomNavItems={mobileNavItems}
      activeNavItem={activeItem}
      onNavItemPress={handleMobileNavPress}
      enablePullToRefresh={true}
      onRefresh={async () => {
        // Simulate refresh
        await new Promise(resolve => setTimeout(resolve, 1000));
      }}
    >
      {dashboardContent}
    </ResponsiveLayout>
  );
}