'use client'

import { useState, useEffect } from 'react'
import { useSession, signIn, signOut } from 'next-auth/react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useAppStore, View } from '@/lib/store'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { 
  Sheet, 
  SheetContent, 
  SheetDescription, 
  SheetHeader, 
  SheetTitle, 
  SheetTrigger 
} from '@/components/ui/sheet'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Progress } from '@/components/ui/progress'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useToast } from '@/hooks/use-toast'
import { 
  Home, 
  ShoppingCart, 
  Package, 
  User, 
  Settings, 
  LogOut, 
  LogIn,
  Menu,
  Search,
  Plus,
  Minus,
  Trash2,
  CheckCircle,
  Clock,
  AlertCircle,
  Truck,
  Factory,
  XCircle,
  Moon,
  Sun,
  Building2,
  Phone,
  Mail,
  MapPin,
  FileText,
  Users,
  RefreshCw,
  ChevronRight,
  Eye,
  Filter,
  SortAsc,
  Calendar,
  Hash,
  LayoutGrid,
  List,
  ArrowUpDown
} from 'lucide-react'
import { useTheme } from 'next-themes'

// ============== SCHEMAS ==============
const registerSchema = z.object({
  email: z.string().email('Некорректный email'),
  password: z.string().min(6, 'Пароль должен быть не менее 6 символов'),
  name: z.string().min(2, 'Имя должно быть не менее 2 символов'),
  phone: z.string().optional(),
  companyName: z.string().optional(),
  companyUnp: z.string().optional(),
  companyAddress: z.string().optional()
})

const orderSchema = z.object({
  deliveryAddress: z.string().min(5, 'Укажите адрес доставки'),
  deliveryDate: z.string().optional(),
  contactPerson: z.string().min(2, 'Укажите контактное лицо'),
  contactPhone: z.string().min(6, 'Укажите контактный телефон'),
  notes: z.string().optional()
})

// ============== TYPES ==============
interface Product {
  id: string
  sku: string
  name: string
  slug: string
  description: string | null
  price: number
  wholesalePrice: number | null
  minWholesaleQty: number
  unit: string
  stock: number
  isAvailable: boolean
  category: { id: string; name: string; slug: string } | null
}

interface CartItem {
  id: string
  quantity: number
  product: Product
}

interface Cart {
  id: string
  items: CartItem[]
}

interface OrderItem {
  id: string
  productName: string
  productSku: string
  productUnit: string
  quantity: number
  price: number
  totalPrice: number
  product: { name: string; sku: string } | null
}

interface Order {
  id: string
  orderNumber: string
  status: string
  source: string
  deliveryAddress: string | null
  deliveryDate: string | null
  contactPerson: string | null
  contactPhone: string | null
  notes: string | null
  subtotal: number
  total: number
  createdAt: string
  items: OrderItem[]
  statusHistory: { status: string; comment: string | null; createdAt: string }[]
}

interface User {
  id: string
  email: string
  name: string | null
  phone: string | null
  companyName: string | null
  companyUnp: string | null
  companyAddress: string | null
  status: string
  role: string
  externalId1C: string | null
  createdAt: string
  activatedAt: string | null
  _count?: { orders: number }
}

// ============== MAIN COMPONENT ==============
export default function Dashboard() {
  const { data: session, status } = useSession()
  const { currentView, setCurrentView, sidebarOpen, setSidebarOpen } = useAppStore()
  const { theme, setTheme } = useTheme()
  const { toast } = useToast()
  const queryClient = useQueryClient()
  const [mounted, setMounted] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [showAuthDialog, setShowAuthDialog] = useState<'login' | 'register' | null>(null)
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null)
  const [catalogView, setCatalogView] = useState<'grid' | 'table'>('table')
  const [currentPage, setCurrentPage] = useState(1)

  useEffect(() => {
    setMounted(true)
  }, [])

  // Reset page when filters change
  useEffect(() => {
    setCurrentPage(1)
  }, [searchQuery, selectedCategory])

  // ============== QUERIES ==============
  const { data: productsData, isLoading: productsLoading } = useQuery({
    queryKey: ['products', searchQuery, selectedCategory, currentPage],
    queryFn: async () => {
      const params = new URLSearchParams()
      if (searchQuery) params.append('search', searchQuery)
      if (selectedCategory) params.append('category', selectedCategory)
      params.append('page', String(currentPage))
      const res = await fetch(`/api/products?${params}`)
      if (!res.ok) throw new Error('Failed to fetch products')
      return res.json()
    },
    enabled: currentView === 'catalog' && !!session
  })

  const { data: categoriesData } = useQuery({
    queryKey: ['categories'],
    queryFn: async () => {
      const res = await fetch('/api/categories')
      if (!res.ok) throw new Error('Failed to fetch categories')
      return res.json()
    },
    enabled: !!session
  })

  const { data: cartData, isLoading: cartLoading } = useQuery({
    queryKey: ['cart'],
    queryFn: async () => {
      const res = await fetch('/api/cart')
      if (!res.ok) throw new Error('Failed to fetch cart')
      return res.json()
    },
    enabled: currentView === 'cart' && !!session
  })

  const { data: ordersData, isLoading: ordersLoading } = useQuery({
    queryKey: ['orders'],
    queryFn: async () => {
      const res = await fetch('/api/orders')
      if (!res.ok) throw new Error('Failed to fetch orders')
      return res.json()
    },
    enabled: currentView === 'orders' && !!session
  })

  const { data: usersData, isLoading: usersLoading } = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const res = await fetch('/api/admin/users')
      if (!res.ok) throw new Error('Failed to fetch users')
      return res.json()
    },
    enabled: currentView === 'admin' && !!session && ['MANAGER', 'ADMIN'].includes(session.user?.role || '')
  })

  // ============== MUTATIONS ==============
  const addToCartMutation = useMutation({
    mutationFn: async ({ productId, quantity }: { productId: string; quantity: number }) => {
      const res = await fetch('/api/cart', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productId, quantity })
      })
      if (!res.ok) throw new Error('Failed to add to cart')
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cart'] })
      toast({ title: 'Добавлено в корзину', description: 'Товар успешно добавлен в корзину' })
    },
    onError: () => {
      toast({ title: 'Ошибка', description: 'Не удалось добавить товар в корзину', variant: 'destructive' })
    }
  })

  const updateCartMutation = useMutation({
    mutationFn: async ({ productId, quantity }: { productId: string; quantity: number }) => {
      const res = await fetch('/api/cart', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productId, quantity })
      })
      if (!res.ok) throw new Error('Failed to update cart')
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cart'] })
    }
  })

  const createOrderMutation = useMutation({
    mutationFn: async (data: z.infer<typeof orderSchema>) => {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      })
      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || 'Failed to create order')
      }
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      queryClient.invalidateQueries({ queryKey: ['cart'] })
      setCurrentView('orders')
      toast({ title: 'Заказ создан', description: 'Ваш заказ успешно оформлен' })
    },
    onError: (error: Error) => {
      toast({ title: 'Ошибка', description: error.message, variant: 'destructive' })
    }
  })

  const activateUserMutation = useMutation({
    mutationFn: async ({ userId, status }: { userId: string; status: string }) => {
      const res = await fetch(`/api/admin/users/${userId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status })
      })
      if (!res.ok) throw new Error('Failed to update user')
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] })
      toast({ title: 'Статус обновлен', description: 'Статус пользователя успешно изменен' })
    }
  })

  // ============== FORMS ==============
  const registerForm = useForm<z.infer<typeof registerSchema>>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      email: '',
      password: '',
      name: '',
      phone: '',
      companyName: '',
      companyUnp: '',
      companyAddress: ''
    }
  })

  const orderForm = useForm<z.infer<typeof orderSchema>>({
    resolver: zodResolver(orderSchema),
    defaultValues: {
      deliveryAddress: '',
      deliveryDate: '',
      contactPerson: session?.user?.name || '',
      contactPhone: '',
      notes: ''
    }
  })

  // ============== HANDLERS ==============
  const handleRegister = async (data: z.infer<typeof registerSchema>) => {
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      })
      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || 'Registration failed')
      }
      setShowAuthDialog(null)
      toast({ 
        title: 'Регистрация успешна', 
        description: 'Ваш аккаунт будет активирован менеджером в ближайшее время. Вы получите уведомление на email.' 
      })
    } catch (error: unknown) {
      toast({ 
        title: 'Ошибка регистрации', 
        description: error instanceof Error ? error.message : 'Неизвестная ошибка',
        variant: 'destructive' 
      })
    }
  }

  const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const formData = new FormData(e.currentTarget)
    const email = formData.get('email') as string
    const password = formData.get('password') as string
    
    const result = await signIn('credentials', {
      email,
      password,
      redirect: false
    })

    if (result?.error) {
      toast({ title: 'Ошибка входа', description: 'Неверный email или пароль', variant: 'destructive' })
    } else {
      setShowAuthDialog(null)
    }
  }

  const handleCreateOrder = (data: z.infer<typeof orderSchema>) => {
    createOrderMutation.mutate(data)
  }

  // ============== HELPERS ==============
  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline'; icon: React.ElementType }> = {
      NEW: { label: 'Новый', variant: 'default', icon: Clock },
      PROCESSING: { label: 'В обработке', variant: 'secondary', icon: RefreshCw },
      CONFIRMED: { label: 'Подтвержден', variant: 'default', icon: CheckCircle },
      IN_PRODUCTION: { label: 'В производстве', variant: 'secondary', icon: Factory },
      READY: { label: 'Готов', variant: 'default', icon: Package },
      SHIPPED: { label: 'Отгружен', variant: 'secondary', icon: Truck },
      DELIVERED: { label: 'Доставлен', variant: 'default', icon: CheckCircle },
      CANCELLED: { label: 'Отменен', variant: 'destructive', icon: XCircle },
      PENDING: { label: 'Ожидает', variant: 'outline', icon: Clock },
      ACTIVE: { label: 'Активен', variant: 'default', icon: CheckCircle },
      SUSPENDED: { label: 'Приостановлен', variant: 'destructive', icon: AlertCircle }
    }
    
    const config = statusConfig[status] || { label: status, variant: 'outline' as const, icon: AlertCircle }
    const Icon = config.icon
    
    return (
      <Badge variant={config.variant} className="gap-1">
        <Icon className="h-3 w-3" />
        {config.label}
      </Badge>
    )
  }

  const getUnitLabel = (unit: string) => {
    const units: Record<string, string> = {
      PIECE: 'шт',
      METER: 'м',
      SQUARE_METER: 'м²',
      KILOGRAM: 'кг',
      PACK: 'упак'
    }
    return units[unit] || unit
  }

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('ru-BY', {
      style: 'currency',
      currency: 'BYN',
      minimumFractionDigits: 2
    }).format(price)
  }

  // ============== RENDER ==============
  if (!mounted) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    )
  }

  // Auth check
  if (status === 'unauthenticated' || !session) {
    return (
      <div className="min-h-screen flex flex-col bg-gradient-to-br from-background via-background to-muted/30">
        {/* Header */}
        <header className="border-b bg-card/80 backdrop-blur-sm sticky top-0 z-50">
          <div className="container mx-auto px-4 h-16 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="h-9 w-9 rounded-lg bg-primary flex items-center justify-center">
                <Home className="h-5 w-5 text-primary-foreground" />
              </div>
              <div>
                <h1 className="font-bold text-lg leading-tight">Кровельный центр</h1>
                <p className="text-xs text-muted-foreground">Личный кабинет</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
              >
                {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
              </Button>
              <Button onClick={() => setShowAuthDialog('login')}>
                <LogIn className="h-4 w-4 mr-2" />
                Войти
              </Button>
            </div>
          </div>
        </header>

        {/* Hero */}
        <main className="flex-1 flex items-center justify-center p-8">
          <div className="max-w-2xl text-center space-y-6">
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 text-primary text-sm font-medium">
              <Building2 className="h-4 w-4" />
              B2B портал для оптовых покупателей
            </div>
            <h1 className="text-4xl md:text-5xl font-bold tracking-tight">
              Кровельные материалы
              <span className="text-primary"> оптом</span>
            </h1>
            <p className="text-xl text-muted-foreground max-w-xl mx-auto">
              Металлочерепица, профнастил, аксессуары для кровли. 
              Прямые поставки от производителя.
            </p>
            <div className="flex flex-col sm:flex-row gap-3 justify-center">
              <Button size="lg" onClick={() => setShowAuthDialog('register')}>
                <User className="h-4 w-4 mr-2" />
                Регистрация
              </Button>
              <Button size="lg" variant="outline" onClick={() => setShowAuthDialog('login')}>
                Уже есть аккаунт? Войти
              </Button>
            </div>
            <div className="flex items-center justify-center gap-8 pt-8 text-sm text-muted-foreground">
              <div className="flex items-center gap-2">
                <CheckCircle className="h-4 w-4 text-primary" />
                Оптовые цены
              </div>
              <div className="flex items-center gap-2">
                <Truck className="h-4 w-4 text-primary" />
                Доставка по РБ
              </div>
              <div className="flex items-center gap-2">
                <Factory className="h-4 w-4 text-primary" />
                От производителя
              </div>
            </div>
          </div>
        </main>

        {/* Footer */}
        <footer className="border-t py-6 bg-card/50">
          <div className="container mx-auto px-4 text-center text-sm text-muted-foreground">
            <p>© 2024 Кровельный центр. Все права защищены.</p>
          </div>
        </footer>

        {/* Auth Dialogs */}
        <Dialog open={showAuthDialog === 'login'} onOpenChange={() => setShowAuthDialog(null)}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Вход в личный кабинет</DialogTitle>
              <DialogDescription>
                Введите email и пароль для доступа к аккаунту
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="login-email">Email</Label>
                <Input id="login-email" name="email" type="email" placeholder="email@company.by" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="login-password">Пароль</Label>
                <Input id="login-password" name="password" type="password" required />
              </div>
              <Button type="submit" className="w-full">Войти</Button>
            </form>
            <div className="text-center text-sm">
              <span className="text-muted-foreground">Нет аккаунта? </span>
              <Button variant="link" className="p-0 h-auto" onClick={() => setShowAuthDialog('register')}>
                Зарегистрироваться
              </Button>
            </div>
          </DialogContent>
        </Dialog>

        <Dialog open={showAuthDialog === 'register'} onOpenChange={() => setShowAuthDialog(null)}>
          <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Регистрация</DialogTitle>
              <DialogDescription>
                Создайте аккаунт для оформления заказов. После регистрации ваш аккаунт будет проверен менеджером.
              </DialogDescription>
            </DialogHeader>
            <Form {...registerForm}>
              <form onSubmit={registerForm.handleSubmit(handleRegister)} className="space-y-4">
                <FormField
                  control={registerForm.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Email *</FormLabel>
                      <FormControl>
                        <Input placeholder="email@company.by" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={registerForm.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Пароль *</FormLabel>
                      <FormControl>
                        <Input type="password" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={registerForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Контактное лицо *</FormLabel>
                      <FormControl>
                        <Input placeholder="Иванов Иван" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={registerForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Телефон</FormLabel>
                      <FormControl>
                        <Input placeholder="+375 29 123-45-67" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <Separator />
                <p className="text-sm text-muted-foreground">Данные организации</p>
                <FormField
                  control={registerForm.control}
                  name="companyName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Название организации</FormLabel>
                      <FormControl>
                        <Input placeholder="ООО Компания" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={registerForm.control}
                  name="companyUnp"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>УНП</FormLabel>
                      <FormControl>
                        <Input placeholder="123456789" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={registerForm.control}
                  name="companyAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Юридический адрес</FormLabel>
                      <FormControl>
                        <Input placeholder="г. Минск, ул. Примерная, 1" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <Button type="submit" className="w-full">Зарегистрироваться</Button>
              </form>
            </Form>
            <div className="text-center text-sm">
              <span className="text-muted-foreground">Уже есть аккаунт? </span>
              <Button variant="link" className="p-0 h-auto" onClick={() => setShowAuthDialog('login')}>
                Войти
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    )
  }

  // Check if user is pending
  if (session.user?.status === 'PENDING') {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <Card className="max-w-md w-full">
          <CardHeader className="text-center">
            <div className="h-16 w-16 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center mx-auto mb-4">
              <Clock className="h-8 w-8 text-amber-600" />
            </div>
            <CardTitle>Аккаунт на модерации</CardTitle>
            <CardDescription>
              Ваш аккаунт ожидает активации менеджером
            </CardDescription>
          </CardHeader>
          <CardContent className="text-center space-y-4">
            <p className="text-sm text-muted-foreground">
              После проверки данных вам придет уведомление на email: <strong>{session.user?.email}</strong>
            </p>
            <Button variant="outline" onClick={() => signOut()} className="w-full">
              <LogOut className="h-4 w-4 mr-2" />
              Выйти
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // Main dashboard
  return (
    <div className="min-h-screen flex flex-col bg-gradient-to-br from-background via-background to-muted/20">
      {/* Header */}
      <header className="border-b bg-card/80 backdrop-blur-sm sticky top-0 z-50">
        <div className="container mx-auto px-4 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon"
              className="md:hidden"
              onClick={() => setSidebarOpen(!sidebarOpen)}
            >
              <Menu className="h-5 w-5" />
            </Button>
            <div className="flex items-center gap-3">
              <div className="h-9 w-9 rounded-lg bg-primary flex items-center justify-center">
                <Home className="h-5 w-5 text-primary-foreground" />
              </div>
              <div className="hidden sm:block">
                <h1 className="font-bold text-lg leading-tight">Кровельный центр</h1>
                <p className="text-xs text-muted-foreground">Личный кабинет</p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {/* Search (only on catalog) */}
            {currentView === 'catalog' && (
              <div className="hidden sm:flex items-center relative">
                <Search className="h-4 w-4 absolute left-3 text-muted-foreground" />
                <Input
                  placeholder="Поиск товаров..."
                  className="pl-9 w-48 lg:w-64"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            )}

            {/* Theme toggle */}
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
            >
              {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
            </Button>

            {/* Cart button */}
            {session.user?.role === 'CLIENT' && (
              <Button
                variant="ghost"
                size="icon"
                className="relative"
                onClick={() => setCurrentView('cart')}
              >
                <ShoppingCart className="h-5 w-5" />
                {cartData?.cart?.items?.length > 0 && (
                  <span className="absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
                    {cartData.cart.items.length}
                  </span>
                )}
              </Button>
            )}

            {/* User menu */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                  <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <User className="h-4 w-4 text-primary" />
                  </div>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <DropdownMenuLabel>
                  <div className="flex flex-col">
                    <span>{session.user?.name || session.user?.email}</span>
                    {session.user?.companyName && (
                      <span className="text-xs text-muted-foreground font-normal">{session.user.companyName}</span>
                    )}
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => setCurrentView('profile')}>
                  <User className="h-4 w-4 mr-2" />
                  Профиль
                </DropdownMenuItem>
                {session.user?.role === 'CLIENT' && (
                  <DropdownMenuItem onClick={() => setCurrentView('orders')}>
                    <Package className="h-4 w-4 mr-2" />
                    Мои заказы
                  </DropdownMenuItem>
                )}
                {['MANAGER', 'ADMIN'].includes(session.user?.role || '') && (
                  <>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={() => setCurrentView('admin')}>
                      <Settings className="h-4 w-4 mr-2" />
                      Управление
                    </DropdownMenuItem>
                  </>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => signOut()} className="text-destructive">
                  <LogOut className="h-4 w-4 mr-2" />
                  Выйти
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </header>

      {/* Main content */}
      <div className="flex-1 flex">
        {/* Sidebar */}
        <aside className={`
          fixed md:sticky top-16 left-0 z-40 h-[calc(100vh-4rem)] w-64 
          bg-card border-r transform transition-transform duration-200 ease-in-out
          ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
          md:translate-x-0
        `}>
          <ScrollArea className="h-full">
            <nav className="p-4 space-y-2">
              <Button
                variant={currentView === 'catalog' ? 'secondary' : 'ghost'}
                className="w-full justify-start"
                onClick={() => setCurrentView('catalog')}
              >
                <Package className="h-4 w-4 mr-2" />
                Каталог
              </Button>

              {session.user?.role === 'CLIENT' && (
                <>
                  <Button
                    variant={currentView === 'cart' ? 'secondary' : 'ghost'}
                    className="w-full justify-start"
                    onClick={() => setCurrentView('cart')}
                  >
                    <ShoppingCart className="h-4 w-4 mr-2" />
                    Корзина
                    {cartData?.cart?.items?.length > 0 && (
                      <Badge variant="secondary" className="ml-auto">{cartData.cart.items.length}</Badge>
                    )}
                  </Button>
                  <Button
                    variant={currentView === 'orders' ? 'secondary' : 'ghost'}
                    className="w-full justify-start"
                    onClick={() => setCurrentView('orders')}
                  >
                    <FileText className="h-4 w-4 mr-2" />
                    Мои заказы
                  </Button>
                </>
              )}

              {['MANAGER', 'ADMIN'].includes(session.user?.role || '') && (
                <>
                  <Separator className="my-4" />
                  <p className="text-xs text-muted-foreground px-2 mb-2">Управление</p>
                  <Button
                    variant={currentView === 'admin' ? 'secondary' : 'ghost'}
                    className="w-full justify-start"
                    onClick={() => setCurrentView('admin')}
                  >
                    <Users className="h-4 w-4 mr-2" />
                    Пользователи
                    {usersData?.users?.filter((u: User) => u.status === 'PENDING').length > 0 && (
                      <Badge variant="destructive" className="ml-auto">
                        {usersData.users.filter((u: User) => u.status === 'PENDING').length}
                      </Badge>
                    )}
                  </Button>
                </>
              )}

              <Separator className="my-4" />

              <Button
                variant={currentView === 'profile' ? 'secondary' : 'ghost'}
                className="w-full justify-start"
                onClick={() => setCurrentView('profile')}
              >
                <User className="h-4 w-4 mr-2" />
                Профиль
              </Button>
            </nav>
          </ScrollArea>
        </aside>

        {/* Mobile sidebar overlay */}
        {sidebarOpen && (
          <div
            className="fixed inset-0 bg-black/50 z-30 md:hidden"
            onClick={() => setSidebarOpen(false)}
          />
        )}

        {/* Main content area */}
        <main className="flex-1 p-4 md:p-6 overflow-auto">
          {/* Catalog View */}
          {currentView === 'catalog' && (
            <div className="space-y-6">
              <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
                <div>
                  <h2 className="text-2xl font-bold">Каталог товаров</h2>
                  <p className="text-muted-foreground">Выберите товары для заказа</p>
                </div>
                <div className="flex gap-2 w-full sm:w-auto">
                  <div className="flex items-center relative flex-1 sm:flex-initial">
                    <Search className="h-4 w-4 absolute left-3 text-muted-foreground" />
                    <Input
                      placeholder="Поиск..."
                      className="pl-9 sm:w-48"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                    />
                  </div>
                  {categoriesData?.categories?.length > 0 && (
                    <Select value={selectedCategory || 'all'} onValueChange={(v) => setSelectedCategory(v === 'all' ? '' : v)}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="Категория" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Все категории</SelectItem>
                        {categoriesData.categories.map((cat: { id: string; name: string }) => (
                          <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  )}
                  {/* View mode toggle */}
                  <div className="flex border rounded-lg overflow-hidden">
                    <Button
                      variant={catalogView === 'grid' ? 'default' : 'ghost'}
                      size="icon"
                      className="rounded-none h-9 w-9"
                      onClick={() => setCatalogView('grid')}
                      title="Плитка"
                    >
                      <LayoutGrid className="h-4 w-4" />
                    </Button>
                    <Button
                      variant={catalogView === 'table' ? 'default' : 'ghost'}
                      size="icon"
                      className="rounded-none h-9 w-9"
                      onClick={() => setCatalogView('table')}
                      title="Таблица"
                    >
                      <List className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </div>

              {productsLoading ? (
                catalogView === 'grid' ? (
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                    {[...Array(8)].map((_, i) => (
                      <Card key={i}>
                        <CardHeader className="pb-2">
                          <div className="h-4 bg-muted rounded animate-pulse" />
                          <div className="h-3 bg-muted rounded w-2/3 animate-pulse" />
                        </CardHeader>
                        <CardContent>
                          <div className="h-20 bg-muted rounded animate-pulse mb-4" />
                          <div className="flex justify-between">
                            <div className="h-6 bg-muted rounded w-20 animate-pulse" />
                            <div className="h-8 bg-muted rounded w-24 animate-pulse" />
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <Card>
                    <CardContent className="p-0">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Артикул</TableHead>
                            <TableHead>Наименование</TableHead>
                            <TableHead>Категория</TableHead>
                            <TableHead className="text-right">Цена</TableHead>
                            <TableHead className="text-right">Опт. цена</TableHead>
                            <TableHead className="text-right">Наличие</TableHead>
                            <TableHead className="w-24"></TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {[...Array(8)].map((_, i) => (
                            <TableRow key={i}>
                              <TableCell><div className="h-4 bg-muted rounded w-20 animate-pulse" /></TableCell>
                              <TableCell><div className="h-4 bg-muted rounded w-40 animate-pulse" /></TableCell>
                              <TableCell><div className="h-4 bg-muted rounded w-20 animate-pulse" /></TableCell>
                              <TableCell><div className="h-4 bg-muted rounded w-16 animate-pulse ml-auto" /></TableCell>
                              <TableCell><div className="h-4 bg-muted rounded w-16 animate-pulse ml-auto" /></TableCell>
                              <TableCell><div className="h-4 bg-muted rounded w-16 animate-pulse ml-auto" /></TableCell>
                              <TableCell><div className="h-8 bg-muted rounded w-16 animate-pulse" /></TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                )
              ) : productsData?.products?.length === 0 ? (
                <Card>
                  <CardContent className="py-12 text-center">
                    <Package className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="font-semibold mb-2">Товары не найдены</h3>
                    <p className="text-muted-foreground">Попробуйте изменить параметры поиска</p>
                  </CardContent>
                </Card>
              ) : catalogView === 'grid' ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                  {productsData?.products?.map((product: Product) => (
                    <Card key={product.id} className="flex flex-col">
                      <CardHeader className="pb-2">
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1">
                            <CardTitle className="text-base leading-tight">{product.name}</CardTitle>
                            <CardDescription className="mt-1">Арт. {product.sku}</CardDescription>
                          </div>
                          {product.category && (
                            <Badge variant="outline" className="shrink-0">{product.category.name}</Badge>
                          )}
                        </div>
                      </CardHeader>
                      <CardContent className="flex-1">
                        <div className="h-24 bg-muted/50 rounded-lg flex items-center justify-center mb-4">
                          <Package className="h-8 w-8 text-muted-foreground/50" />
                        </div>
                        <div className="space-y-2">
                          <div className="flex items-baseline justify-between">
                            <div>
                              <span className="text-xl font-bold">{formatPrice(product.price)}</span>
                              <span className="text-sm text-muted-foreground ml-1">/{getUnitLabel(product.unit)}</span>
                            </div>
                            {product.stock > 0 ? (
                              <Badge variant="secondary" className="text-green-700 dark:text-green-400 bg-green-100 dark:bg-green-900/30">
                                В наличии
                              </Badge>
                            ) : (
                              <Badge variant="outline" className="text-muted-foreground">Под заказ</Badge>
                            )}
                          </div>
                          {product.wholesalePrice && (
                            <p className="text-xs text-primary">
                              Опт от {product.minWholesaleQty} {getUnitLabel(product.unit)}: {formatPrice(product.wholesalePrice)}
                            </p>
                          )}
                        </div>
                      </CardContent>
                      <CardFooter className="pt-0">
                        <Button 
                          className="w-full" 
                          onClick={() => addToCartMutation.mutate({ productId: product.id, quantity: 1 })}
                          disabled={!product.isAvailable}
                        >
                          <Plus className="h-4 w-4 mr-2" />
                          В корзину
                        </Button>
                      </CardFooter>
                    </Card>
                  ))}
                </div>
              ) : (
                <Card>
                  <CardContent className="p-0">
                    <div className="overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-32">Артикул</TableHead>
                            <TableHead>Наименование</TableHead>
                            <TableHead className="w-36">Категория</TableHead>
                            <TableHead className="text-right w-28">Розн. цена</TableHead>
                            <TableHead className="text-right w-36">Опт. цена</TableHead>
                            <TableHead className="text-right w-24">Наличие</TableHead>
                            <TableHead className="w-28"></TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {productsData?.products?.map((product: Product) => (
                            <TableRow key={product.id} className="group">
                              <TableCell className="font-mono text-sm">{product.sku}</TableCell>
                              <TableCell>
                                <div>
                                  <p className="font-medium">{product.name}</p>
                                  {product.description && (
                                    <p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">{product.description}</p>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell>
                                {product.category && (
                                  <Badge variant="outline" className="text-xs">{product.category.name}</Badge>
                                )}
                              </TableCell>
                              <TableCell className="text-right">
                                <div>
                                  <span className="font-semibold">{formatPrice(product.price)}</span>
                                  <span className="text-xs text-muted-foreground block">/{getUnitLabel(product.unit)}</span>
                                </div>
                              </TableCell>
                              <TableCell className="text-right">
                                {product.wholesalePrice ? (
                                  <div>
                                    <span className="font-semibold text-primary">{formatPrice(product.wholesalePrice)}</span>
                                    <span className="text-xs text-muted-foreground block">от {product.minWholesaleQty} {getUnitLabel(product.unit)}</span>
                                  </div>
                                ) : (
                                  <span className="text-muted-foreground">—</span>
                                )}
                              </TableCell>
                              <TableCell className="text-right">
                                {product.stock > 0 ? (
                                  <div>
                                    <Badge variant="secondary" className="text-green-700 dark:text-green-400 bg-green-100 dark:bg-green-900/30">
                                      В наличии
                                    </Badge>
                                    <span className="text-xs text-muted-foreground block mt-1">{product.stock} {getUnitLabel(product.unit)}</span>
                                  </div>
                                ) : (
                                  <Badge variant="outline" className="text-muted-foreground">Под заказ</Badge>
                                )}
                              </TableCell>
                              <TableCell>
                                <Button 
                                  size="sm"
                                  onClick={() => addToCartMutation.mutate({ productId: product.id, quantity: 1 })}
                                  disabled={!product.isAvailable}
                                  className="opacity-0 group-hover:opacity-100 transition-opacity"
                                >
                                  <Plus className="h-4 w-4 mr-1" />
                                  В корзину
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Pagination */}
              {productsData?.pagination?.totalPages > 1 && (
                <div className="flex justify-center gap-2">
                  <Button 
                    variant="outline" 
                    disabled={productsData.pagination.page === 1}
                    onClick={() => setCurrentPage(p => p - 1)}
                  >
                    Назад
                  </Button>
                  <span className="flex items-center px-4 text-sm text-muted-foreground">
                    {productsData.pagination.page} / {productsData.pagination.totalPages}
                  </span>
                  <Button 
                    variant="outline" 
                    disabled={productsData.pagination.page === productsData.pagination.totalPages}
                    onClick={() => setCurrentPage(p => p + 1)}
                  >
                    Вперёд
                  </Button>
                </div>
              )}
            </div>
          )}

          {/* Cart View */}
          {currentView === 'cart' && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold">Корзина</h2>
                <p className="text-muted-foreground">Проверьте заказ перед оформлением</p>
              </div>

              {cartLoading ? (
                <Card>
                  <CardContent className="py-12">
                    <div className="animate-pulse space-y-4">
                      {[...Array(3)].map((_, i) => (
                        <div key={i} className="flex gap-4">
                          <div className="h-20 w-20 bg-muted rounded" />
                          <div className="flex-1 space-y-2">
                            <div className="h-4 bg-muted rounded w-1/2" />
                            <div className="h-3 bg-muted rounded w-1/4" />
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              ) : !cartData?.cart?.items?.length ? (
                <Card>
                  <CardContent className="py-12 text-center">
                    <ShoppingCart className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="font-semibold mb-2">Корзина пуста</h3>
                    <p className="text-muted-foreground mb-4">Добавьте товары из каталога</p>
                    <Button onClick={() => setCurrentView('catalog')}>
                      Перейти в каталог
                    </Button>
                  </CardContent>
                </Card>
              ) : (
                <div className="grid lg:grid-cols-3 gap-6">
                  <div className="lg:col-span-2 space-y-4">
                    {cartData.cart.items.map((item: CartItem) => (
                      <Card key={item.id}>
                        <CardContent className="p-4">
                          <div className="flex gap-4">
                            <div className="h-20 w-20 bg-muted rounded-lg flex items-center justify-center shrink-0">
                              <Package className="h-8 w-8 text-muted-foreground/50" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <h4 className="font-medium truncate">{item.product.name}</h4>
                              <p className="text-sm text-muted-foreground">Арт. {item.product.sku}</p>
                              <div className="flex items-center gap-4 mt-2">
                                <div className="flex items-center gap-2">
                                  <Button
                                    variant="outline"
                                    size="icon"
                                    className="h-8 w-8"
                                    onClick={() => updateCartMutation.mutate({
                                      productId: item.productId,
                                      quantity: item.quantity - 1
                                    })}
                                  >
                                    <Minus className="h-3 w-3" />
                                  </Button>
                                  <span className="w-12 text-center">{item.quantity}</span>
                                  <Button
                                    variant="outline"
                                    size="icon"
                                    className="h-8 w-8"
                                    onClick={() => updateCartMutation.mutate({
                                      productId: item.productId,
                                      quantity: item.quantity + 1
                                    })}
                                  >
                                    <Plus className="h-3 w-3" />
                                  </Button>
                                  <span className="text-sm text-muted-foreground">{getUnitLabel(item.product.unit)}</span>
                                </div>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-8 w-8 text-destructive"
                                  onClick={() => updateCartMutation.mutate({
                                    productId: item.productId,
                                    quantity: 0
                                  })}
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                            <div className="text-right">
                              <p className="font-bold">
                                {formatPrice(item.product.price * item.quantity)}
                              </p>
                              {item.product.wholesalePrice && item.quantity >= item.product.minWholesaleQty && (
                                <p className="text-xs text-primary">
                                  Оптовая цена применена
                                </p>
                              )}
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>

                  <div className="lg:col-span-1">
                    <Card className="sticky top-20">
                      <CardHeader>
                        <CardTitle>Оформление заказа</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <Form {...orderForm}>
                          <form onSubmit={orderForm.handleSubmit(handleCreateOrder)} className="space-y-4">
                            <FormField
                              control={orderForm.control}
                              name="deliveryAddress"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>Адрес доставки</FormLabel>
                                  <FormControl>
                                    <Input placeholder="г. Минск, ул. Примерная, 1" {...field} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={orderForm.control}
                              name="contactPerson"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>Контактное лицо</FormLabel>
                                  <FormControl>
                                    <Input placeholder="Иванов Иван" {...field} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={orderForm.control}
                              name="contactPhone"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>Телефон</FormLabel>
                                  <FormControl>
                                    <Input placeholder="+375 29 123-45-67" {...field} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={orderForm.control}
                              name="deliveryDate"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>Желаемая дата доставки</FormLabel>
                                  <FormControl>
                                    <Input type="date" {...field} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={orderForm.control}
                              name="notes"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>Комментарий</FormLabel>
                                  <FormControl>
                                    <Textarea placeholder="Дополнительная информация" {...field} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            
                            <Separator />
                            
                            <div className="space-y-2">
                              <div className="flex justify-between text-sm">
                                <span className="text-muted-foreground">Товаров:</span>
                                <span>{cartData.cart.items.length} позиций</span>
                              </div>
                              <div className="flex justify-between font-bold text-lg">
                                <span>Итого:</span>
                                <span>
                                  {formatPrice(
                                    cartData.cart.items.reduce((sum: number, item: CartItem) => {
                                      const price = item.product.wholesalePrice && item.quantity >= item.product.minWholesaleQty
                                        ? item.product.wholesalePrice
                                        : item.product.price
                                      return sum + price * item.quantity
                                    }, 0)
                                  )}
                                </span>
                              </div>
                            </div>

                            <Button 
                              type="submit" 
                              className="w-full" 
                              disabled={createOrderMutation.isPending}
                            >
                              {createOrderMutation.isPending ? (
                                <><RefreshCw className="h-4 w-4 mr-2 animate-spin" />Оформление...</>
                              ) : (
                                'Оформить заказ'
                              )}
                            </Button>
                          </form>
                        </Form>
                      </CardContent>
                    </Card>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Orders View */}
          {currentView === 'orders' && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold">Мои заказы</h2>
                <p className="text-muted-foreground">История заказов и их статусы</p>
              </div>

              {ordersLoading ? (
                <div className="space-y-4">
                  {[...Array(3)].map((_, i) => (
                    <Card key={i}>
                      <CardContent className="py-4">
                        <div className="animate-pulse flex gap-4">
                          <div className="h-10 w-24 bg-muted rounded" />
                          <div className="flex-1 space-y-2">
                            <div className="h-4 bg-muted rounded w-1/4" />
                            <div className="h-3 bg-muted rounded w-1/3" />
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              ) : !ordersData?.orders?.length ? (
                <Card>
                  <CardContent className="py-12 text-center">
                    <Package className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="font-semibold mb-2">Заказов пока нет</h3>
                    <p className="text-muted-foreground mb-4">Оформите первый заказ из каталога</p>
                    <Button onClick={() => setCurrentView('catalog')}>
                      Перейти в каталог
                    </Button>
                  </CardContent>
                </Card>
              ) : (
                <div className="space-y-4">
                  {ordersData.orders.map((order: Order) => (
                    <Card key={order.id}>
                      <CardContent className="p-4">
                        <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                          <div className="flex items-center gap-3">
                            <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                              <Hash className="h-5 w-5 text-primary" />
                            </div>
                            <div>
                              <p className="font-semibold">{order.orderNumber}</p>
                              <p className="text-xs text-muted-foreground">
                                {new Date(order.createdAt).toLocaleDateString('ru-BY')}
                              </p>
                            </div>
                          </div>
                          <div className="flex-1" />
                          {getStatusBadge(order.status)}
                          <div className="text-right">
                            <p className="font-bold">{formatPrice(order.total)}</p>
                            <p className="text-xs text-muted-foreground">{order.items.length} позиций</p>
                          </div>
                          <Dialog>
                            <DialogTrigger asChild>
                              <Button variant="outline" size="sm" onClick={() => setSelectedOrder(order)}>
                                <Eye className="h-4 w-4 mr-2" />
                                Подробнее
                              </Button>
                            </DialogTrigger>
                            <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
                              <DialogHeader>
                                <DialogTitle>Заказ {order.orderNumber}</DialogTitle>
                                <DialogDescription>
                                  от {new Date(order.createdAt).toLocaleDateString('ru-BY')}
                                </DialogDescription>
                              </DialogHeader>
                              <div className="space-y-4">
                                <div className="flex items-center gap-2">
                                  {getStatusBadge(order.status)}
                                  <Badge variant="outline">
                                    {order.source === 'WEBSITE' ? 'Оформлен на сайте' : 'Оформлен в 1С'}
                                  </Badge>
                                </div>
                                
                                <Separator />
                                
                                <div className="grid sm:grid-cols-2 gap-4 text-sm">
                                  {order.deliveryAddress && (
                                    <div className="flex items-start gap-2">
                                      <MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />
                                      <span>{order.deliveryAddress}</span>
                                    </div>
                                  )}
                                  {order.contactPerson && (
                                    <div className="flex items-start gap-2">
                                      <User className="h-4 w-4 text-muted-foreground mt-0.5" />
                                      <span>{order.contactPerson}</span>
                                    </div>
                                  )}
                                  {order.contactPhone && (
                                    <div className="flex items-start gap-2">
                                      <Phone className="h-4 w-4 text-muted-foreground mt-0.5" />
                                      <span>{order.contactPhone}</span>
                                    </div>
                                  )}
                                  {order.deliveryDate && (
                                    <div className="flex items-start gap-2">
                                      <Calendar className="h-4 w-4 text-muted-foreground mt-0.5" />
                                      <span>{new Date(order.deliveryDate).toLocaleDateString('ru-BY')}</span>
                                    </div>
                                  )}
                                </div>

                                {order.notes && (
                                  <>
                                    <Separator />
                                    <div className="text-sm">
                                      <p className="font-medium mb-1">Комментарий:</p>
                                      <p className="text-muted-foreground">{order.notes}</p>
                                    </div>
                                  </>
                                )}

                                <Separator />
                                
                                <div>
                                  <h4 className="font-medium mb-2">Товары</h4>
                                  <Table>
                                    <TableHeader>
                                      <TableRow>
                                        <TableHead>Товар</TableHead>
                                        <TableHead className="text-right">Кол-во</TableHead>
                                        <TableHead className="text-right">Цена</TableHead>
                                        <TableHead className="text-right">Сумма</TableHead>
                                      </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                      {order.items.map((item) => (
                                        <TableRow key={item.id}>
                                          <TableCell>
                                            <div>
                                              <p className="font-medium">{item.productName}</p>
                                              <p className="text-xs text-muted-foreground">Арт. {item.productSku}</p>
                                            </div>
                                          </TableCell>
                                          <TableCell className="text-right">
                                            {item.quantity} {getUnitLabel(item.productUnit)}
                                          </TableCell>
                                          <TableCell className="text-right">{formatPrice(item.price)}</TableCell>
                                          <TableCell className="text-right font-medium">{formatPrice(item.totalPrice)}</TableCell>
                                        </TableRow>
                                      ))}
                                    </TableBody>
                                  </Table>
                                </div>

                                <div className="flex justify-between items-center pt-4 border-t">
                                  <span className="font-medium">Итого:</span>
                                  <span className="text-xl font-bold">{formatPrice(order.total)}</span>
                                </div>

                                {order.statusHistory.length > 0 && (
                                  <>
                                    <Separator />
                                    <div>
                                      <h4 className="font-medium mb-2">История статусов</h4>
                                      <div className="space-y-2">
                                        {order.statusHistory.map((h, i) => (
                                          <div key={i} className="flex items-center gap-2 text-sm">
                                            <div className="h-2 w-2 rounded-full bg-primary" />
                                            {getStatusBadge(h.status)}
                                            <span className="text-muted-foreground">
                                              {new Date(h.createdAt).toLocaleString('ru-BY')}
                                            </span>
                                            {h.comment && (
                                              <span className="text-muted-foreground">- {h.comment}</span>
                                            )}
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  </>
                                )}
                              </div>
                            </DialogContent>
                          </Dialog>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Profile View */}
          {currentView === 'profile' && (
            <div className="space-y-6 max-w-2xl">
              <div>
                <h2 className="text-2xl font-bold">Профиль</h2>
                <p className="text-muted-foreground">Ваши личные данные</p>
              </div>

              <Card>
                <CardHeader>
                  <CardTitle>Основная информация</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center gap-4">
                    <div className="h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center">
                      <User className="h-8 w-8 text-primary" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg">{session.user?.name || 'Не указано'}</h3>
                      <p className="text-muted-foreground">{session.user?.email}</p>
                      {getStatusBadge(session.user?.status || 'PENDING')}
                    </div>
                  </div>
                </CardContent>
              </Card>

              {session.user?.companyName && (
                <Card>
                  <CardHeader>
                    <CardTitle>Данные организации</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid sm:grid-cols-2 gap-4">
                      <div className="flex items-start gap-3">
                        <Building2 className="h-5 w-5 text-muted-foreground mt-0.5" />
                        <div>
                          <p className="text-sm text-muted-foreground">Организация</p>
                          <p className="font-medium">{session.user.companyName}</p>
                        </div>
                      </div>
                      {session.user.companyUnp && (
                        <div className="flex items-start gap-3">
                          <Hash className="h-5 w-5 text-muted-foreground mt-0.5" />
                          <div>
                            <p className="text-sm text-muted-foreground">УНП</p>
                            <p className="font-medium">{session.user.companyUnp}</p>
                          </div>
                        </div>
                      )}
                      {session.user.companyAddress && (
                        <div className="flex items-start gap-3 sm:col-span-2">
                          <MapPin className="h-5 w-5 text-muted-foreground mt-0.5" />
                          <div>
                            <p className="text-sm text-muted-foreground">Адрес</p>
                            <p className="font-medium">{session.user.companyAddress}</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )}

              <Card>
                <CardHeader>
                  <CardTitle>Безопасность</CardTitle>
                </CardHeader>
                <CardContent>
                  <Button variant="outline">
                    Изменить пароль
                  </Button>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Admin View */}
          {currentView === 'admin' && ['MANAGER', 'ADMIN'].includes(session.user?.role || '') && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold">Управление пользователями</h2>
                <p className="text-muted-foreground">Модерация и управление клиентами</p>
              </div>

              <Tabs defaultValue="pending">
                <TabsList>
                  <TabsTrigger value="pending">
                    Ожидают активации
                    {usersData?.users?.filter((u: User) => u.status === 'PENDING').length > 0 && (
                      <Badge variant="destructive" className="ml-2">
                        {usersData.users.filter((u: User) => u.status === 'PENDING').length}
                      </Badge>
                    )}
                  </TabsTrigger>
                  <TabsTrigger value="all">Все пользователи</TabsTrigger>
                </TabsList>

                <TabsContent value="pending" className="mt-4">
                  {usersLoading ? (
                    <Card>
                      <CardContent className="py-12 text-center">
                        <RefreshCw className="h-6 w-6 animate-spin mx-auto text-muted-foreground" />
                      </CardContent>
                    </Card>
                  ) : !usersData?.users?.filter((u: User) => u.status === 'PENDING').length ? (
                    <Card>
                      <CardContent className="py-12 text-center">
                        <CheckCircle className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                        <h3 className="font-semibold mb-2">Все заявки обработаны</h3>
                        <p className="text-muted-foreground">Нет пользователей, ожидающих активации</p>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="space-y-4">
                      {usersData.users
                        .filter((u: User) => u.status === 'PENDING')
                        .map((user: User) => (
                        <Card key={user.id}>
                          <CardContent className="p-4">
                            <div className="flex flex-col sm:flex-row gap-4">
                              <div className="flex items-center gap-3">
                                <div className="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
                                  <Clock className="h-5 w-5 text-amber-600" />
                                </div>
                                <div>
                                  <p className="font-semibold">{user.name}</p>
                                  <p className="text-sm text-muted-foreground">{user.email}</p>
                                </div>
                              </div>
                              <div className="flex-1" />
                              <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                                {user.companyName && (
                                  <div className="flex items-center gap-1">
                                    <Building2 className="h-4 w-4" />
                                    {user.companyName}
                                  </div>
                                )}
                                {user.companyUnp && (
                                  <div className="flex items-center gap-1">
                                    <Hash className="h-4 w-4" />
                                    УНП: {user.companyUnp}
                                  </div>
                                )}
                                {user.phone && (
                                  <div className="flex items-center gap-1">
                                    <Phone className="h-4 w-4" />
                                    {user.phone}
                                  </div>
                                )}
                              </div>
                              <div className="flex gap-2">
                                <Button
                                  size="sm"
                                  onClick={() => activateUserMutation.mutate({ userId: user.id, status: 'ACTIVE' })}
                                  disabled={activateUserMutation.isPending}
                                >
                                  <CheckCircle className="h-4 w-4 mr-2" />
                                  Активировать
                                </Button>
                                <AlertDialog>
                                  <AlertDialogTrigger asChild>
                                    <Button size="sm" variant="destructive">
                                      <XCircle className="h-4 w-4 mr-2" />
                                      Отклонить
                                    </Button>
                                  </AlertDialogTrigger>
                                  <AlertDialogContent>
                                    <AlertDialogHeader>
                                      <AlertDialogTitle>Отклонить заявку?</AlertDialogTitle>
                                      <AlertDialogDescription>
                                        Пользователь {user.name} не будет активирован.
                                      </AlertDialogDescription>
                                    </AlertDialogHeader>
                                    <AlertDialogFooter>
                                      <AlertDialogCancel>Отмена</AlertDialogCancel>
                                      <AlertDialogAction
                                        onClick={() => activateUserMutation.mutate({ userId: user.id, status: 'SUSPENDED' })}
                                      >
                                        Отклонить
                                      </AlertDialogAction>
                                    </AlertDialogFooter>
                                  </AlertDialogContent>
                                </AlertDialog>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="all" className="mt-4">
                  <Card>
                    <CardContent className="p-0">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Пользователь</TableHead>
                            <TableHead>Организация</TableHead>
                            <TableHead>Статус</TableHead>
                            <TableHead>Заказов</TableHead>
                            <TableHead>Дата регистрации</TableHead>
                            <TableHead></TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {usersLoading ? (
                            <TableRow>
                              <TableCell colSpan={6} className="text-center py-8">
                                <RefreshCw className="h-6 w-6 animate-spin mx-auto text-muted-foreground" />
                              </TableCell>
                            </TableRow>
                          ) : usersData?.users?.map((user: User) => (
                            <TableRow key={user.id}>
                              <TableCell>
                                <div>
                                  <p className="font-medium">{user.name}</p>
                                  <p className="text-xs text-muted-foreground">{user.email}</p>
                                </div>
                              </TableCell>
                              <TableCell>
                                {user.companyName ? (
                                  <div>
                                    <p>{user.companyName}</p>
                                    {user.companyUnp && (
                                      <p className="text-xs text-muted-foreground">УНП: {user.companyUnp}</p>
                                    )}
                                  </div>
                                ) : (
                                  <span className="text-muted-foreground">—</span>
                                )}
                              </TableCell>
                              <TableCell>{getStatusBadge(user.status)}</TableCell>
                              <TableCell>{user._count?.orders || 0}</TableCell>
                              <TableCell>
                                {new Date(user.createdAt).toLocaleDateString('ru-BY')}
                              </TableCell>
                              <TableCell>
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="sm">
                                      Действия
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent>
                                    <DropdownMenuItem
                                      onClick={() => activateUserMutation.mutate({ userId: user.id, status: 'ACTIVE' })}
                                      disabled={user.status === 'ACTIVE'}
                                    >
                                      <CheckCircle className="h-4 w-4 mr-2" />
                                      Активировать
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                      onClick={() => activateUserMutation.mutate({ userId: user.id, status: 'SUSPENDED' })}
                                      disabled={user.status === 'SUSPENDED'}
                                      className="text-destructive"
                                    >
                                      <AlertCircle className="h-4 w-4 mr-2" />
                                      Приостановить
                                    </DropdownMenuItem>
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </div>
          )}
        </main>
      </div>

      {/* Footer */}
      <footer className="border-t py-4 bg-card/50 mt-auto">
        <div className="container mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-2 text-sm text-muted-foreground">
          <p>© 2024 Кровельный центр. Все права защищены.</p>
          <div className="flex items-center gap-4">
            <a href="tel:+375171234567" className="flex items-center gap-1 hover:text-foreground">
              <Phone className="h-4 w-4" />
              +375 17 123-45-67
            </a>
            <a href="mailto:info@krovlia.by" className="flex items-center gap-1 hover:text-foreground">
              <Mail className="h-4 w-4" />
              info@krovlia.by
            </a>
          </div>
        </div>
      </footer>
    </div>
  )
}
