'use client'

import { useState } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { useToast } from "@/components/ui/use-toast"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { 
  BarChart2, 
  BookOpen, 
  LogOut, 
  Settings, 
  Layout as LayoutIcon, 
  HomeIcon, 
  ClockIcon, 
  CalendarIcon, 
  Plus,
  User, 
  CreditCard, 
  Gift, 
  MessageSquare, 
  Phone,
  BookText,
  ChevronLeft,
  ChevronRight
} from "lucide-react"

const tabs = [
  { id: 'overview', label: 'Overview', icon: HomeIcon, path: '/dashboard' },
  { id: 'time-metrics', label: 'Time Metrics', icon: ClockIcon, path: '/dashboard/time-metrics' },
  { id: 'analytics', label: 'Analytics', icon: BarChart2, path: '/dashboard/analytics' },
  { id: 'calendar', label: 'Calendar', icon: CalendarIcon, path: '/dashboard/calendar' }
]

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const pathname = usePathname()
  const { toast } = useToast()
  const [isCollapsed, setIsCollapsed] = useState(false)
  const [loading, setLoading] = useState(false)
  const [open, setOpen] = useState(false)
  const [tradeData, setTradeData] = useState({
    symbol: '',
    type: 'LONG' as 'LONG' | 'SHORT',
    entry_price: '',
    exit_price: '',
    quantity: '',
    entry_date: '',
    exit_date: '',
    notes: ''
  })
  const [user, setUser] = useState({
    name: 'John Doe',
    email: 'john@example.com'
  })

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', {
        method: 'POST'
      })
      window.location.href = '/login'
    } catch (error) {
      console.error('Logout failed:', error)
    }
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setLoading(true)

    try {
      const payload = {
        ...tradeData,
        entry_price: parseFloat(tradeData.entry_price),
        exit_price: parseFloat(tradeData.exit_price),
        quantity: parseFloat(tradeData.quantity),
      }

      const res = await fetch('/api/trades', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      })

      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.message || 'Failed to add trade')
      }

      toast({
        title: "Success",
        description: "Trade added successfully"
      })

      setOpen(false)
      // Reset trade data
      setTradeData({
        symbol: '',
        type: 'LONG',
        entry_price: '',
        exit_price: '',
        quantity: '',
        entry_date: '',
        exit_date: '',
        notes: ''
      })
    } catch (error: any) {
      toast({
        title: "Error",
        description: error.message || "Failed to add trade",
        variant: "destructive"
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex dark:bg-gray-900">
      {/* Collapsible Sidebar */}
      <div 
        className={`fixed inset-y-0 bg-white dark:bg-gray-800 border-r dark:border-gray-700 flex flex-col transition-all duration-300 ease-in-out ${
          isCollapsed ? 'w-16' : 'w-64'
        }`}
      >
        {/* Logo Section */}
        <div className="p-4 flex items-center">
          <Link href="/dashboard" className="flex items-center">
            <BookOpen className="h-6 w-6 flex-shrink-0" />
            <span className={`ml-2 font-bold text-xl overflow-hidden transition-all duration-300 ease-in-out ${
              isCollapsed ? 'w-0 opacity-0' : 'w-40 opacity-100'
            }`}>
              TradeJournal
            </span>
          </Link>
        </div>

        {/* Add Trade Button */}
        <div className="p-4">
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
              {isCollapsed ? (
                <Button size="icon" className="w-8 h-8">
                  <Plus className="h-4 w-4" />
                </Button>
              ) : (
                <Button 
                  className="w-full bg-blue-500 hover:bg-blue-600 text-white flex items-center justify-center"
                  onClick={() => setOpen(true)}
                >
                  <Plus className="mr-2 h-4 w-4" />
                  Add Trade
                </Button>
              )}
            </DialogTrigger>
            <DialogContent className="sm:max-w-[600px]">
              <DialogHeader>
                <DialogTitle>Add New Trade</DialogTitle>
              </DialogHeader>
              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="symbol">Symbol</Label>
                    <Input
                      id="symbol"
                      value={tradeData.symbol}
                      onChange={(e) => setTradeData({ ...tradeData, symbol: e.target.value.toUpperCase() })}
                      placeholder="AAPL"
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="type">Type</Label>
                    <Select
                      value={tradeData.type}
                      onValueChange={(value: 'LONG' | 'SHORT') => setTradeData({ ...tradeData, type: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select type" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="LONG">Long</SelectItem>
                        <SelectItem value="SHORT">Short</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="entry_price">Entry Price</Label>
                    <Input
                      id="entry_price"
                      type="number"
                      step="0.01"
                      value={tradeData.entry_price}
                      onChange={(e) => setTradeData({ ...tradeData, entry_price: e.target.value })}
                      placeholder="100.00"
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="exit_price">Exit Price</Label>
                    <Input
                      id="exit_price"
                      type="number"
                      step="0.01"
                      value={tradeData.exit_price}
                      onChange={(e) => setTradeData({ ...tradeData, exit_price: e.target.value })}
                      placeholder="110.00"
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="quantity">Quantity</Label>
                    <Input
                      id="quantity"
                      type="number"
                      step="0.01"
                      value={tradeData.quantity}
                      onChange={(e) => setTradeData({ ...tradeData, quantity: e.target.value })}
                      placeholder="100"
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="entry_date">Entry Date</Label>
                    <Input
                      id="entry_date"
                      type="datetime-local"
                      value={tradeData.entry_date}
                      onChange={(e) => setTradeData({ ...tradeData, entry_date: e.target.value })}
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="exit_date">Exit Date</Label>
                    <Input
                      id="exit_date"
                      type="datetime-local"
                      value={tradeData.exit_date}
                      onChange={(e) => setTradeData({ ...tradeData, exit_date: e.target.value })}
                      required
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="notes">Notes</Label>
                  <Textarea
                    id="notes"
                    value={tradeData.notes}
                    onChange={(e) => setTradeData({ ...tradeData, notes: e.target.value })}
                    placeholder="Add your trade notes here..."
                    className="min-h-[100px]"
                  />
                </div>

                <div className="flex justify-end space-x-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setOpen(false)}
                    disabled={loading}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? 'Adding...' : 'Add Trade'}
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Main Navigation */}
        <nav className="flex-1 overflow-y-auto p-4">
          <div className="space-y-1">
            {[
              { href: '/dashboard', icon: LayoutIcon, label: 'Dashboard' },
              { href: '/dashboard/trades', icon: BookOpen, label: 'Trades' },
              { href: '/dashboard/journal', icon: BookText, label: 'Trading Journal' },
              { href: '/dashboard/analytics', icon: BarChart2, label: 'Analytics' },
              { href: '/dashboard/settings', icon: Settings, label: 'Settings' }
            ].map((item) => (
              <Link 
                key={item.href}
                href={item.href} 
                className={`flex items-center h-10 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 ${
                  pathname === item.href ? 'bg-gray-200 dark:bg-gray-700' : ''
                }`}
              >
                <div className="flex items-center px-2">
                  <item.icon className="h-5 w-5 flex-shrink-0" />
                  <span className={`overflow-hidden transition-all duration-300 ease-in-out ${
                    isCollapsed ? 'w-0 opacity-0 ml-0' : 'w-40 opacity-100 ml-2'
                  }`}>
                    {item.label}
                  </span>
                </div>
              </Link>
            ))}
          </div>
        </nav>

        {/* User Profile Section */}
        <div className="p-4">
          {isCollapsed ? (
            <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
              {user.name.charAt(0)}
            </div>
          ) : (
            <DropdownMenu>
              <DropdownMenuTrigger className="w-full">
                <div className="flex items-center space-x-3 p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                  <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                    {user.name.charAt(0)}
                  </div>
                  <div className={`text-left transition-all duration-300 ease-in-out overflow-hidden ${
                    isCollapsed ? 'w-0 opacity-0' : 'w-32 opacity-100'
                  }`}>
                    <p className="font-medium truncate">{user.name}</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400 truncate">{user.email}</p>
                  </div>
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56" align="end">
                <DropdownMenuLabel>My Account</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem>
                  <User className="mr-2 h-4 w-4" />
                  <span>Account Info</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <CreditCard className="mr-2 h-4 w-4" />
                  <span>Manage Billing</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Gift className="mr-2 h-4 w-4" />
                  <span>Upgrade to Pro</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <MessageSquare className="mr-2 h-4 w-4" />
                  <span>Feature Request</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Phone className="mr-2 h-4 w-4" />
                  <span>Get Mobile App</span>
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleLogout}>
                  <LogOut className="mr-2 h-4 w-4" />
                  <span>Log out</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>

        {/* Collapse Toggle Button */}
        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className="absolute -right-3 top-1/2 transform -translate-y-1/2 w-6 h-6 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-full flex items-center justify-center hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
        >
          {isCollapsed ? (
            <ChevronRight className="h-4 w-4" />
          ) : (
            <ChevronLeft className="h-4 w-4" />
          )}
        </button>
      </div>

      {/* Main Content - With dynamic offset for collapsed sidebar */}
      <div className={`flex-1 transition-all duration-300 ease-in-out ${isCollapsed ? 'ml-16' : 'ml-64'}`}>
        <header className="sticky top-0 z-10 bg-white dark:bg-gray-800 border-b dark:border-gray-700">
          <div className="p-4">
            <h1 className="text-2xl font-bold">Dashboard</h1>
          </div>
          {/* Tab Navigation */}
          <div className="px-4 border-t border-gray-700">
            <div className="flex space-x-4">
              {tabs.map(tab => {
                const IconComponent = tab.icon
                const isActive = pathname === tab.path
                return (
                  <Link
                    key={tab.id}
                    href={tab.path}
                    className={`flex items-center space-x-2 px-4 py-2 text-sm border-b-2 ${
                      isActive 
                        ? 'border-blue-500 text-blue-500' 
                        : 'border-transparent text-gray-400 hover:text-gray-300'
                    }`}
                  >
                    <IconComponent className="h-4 w-4" />
                    <span>{tab.label}</span>
                  </Link>
                )
              })}
            </div>
          </div>
        </header>
        <main className="p-6">
          {children}
        </main>
      </div>
    </div>
  )
}


take the code i gave you and update it following these instructions:'use client'

import React from 'react';
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";

export default function Dashboard() {
  const [isCollapsed, setIsCollapsed] = React.useState(false);
  // ... rest of your existing state declarations

  return (
    <div className="p-6 space-y-6 dark:bg-gray-900 min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">Trading Journal</h1>
        
        {/* Conditional Add Trade button that only appears when sidebar is collapsed */}
        {isCollapsed && (
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
              <Button 
                className="bg-blue-500 hover:bg-blue-600 text-white"
                onClick={() => setOpen(true)}
              >
                <Plus className="mr-2 h-4 w-4" />
                Add Trade
              </Button>
            </DialogTrigger>
            {/* Your existing DialogContent component here */}
          </Dialog>
        )}
      </div>

      <div className="flex justify-between items-center mb-4">
        <div className="space-x-2">
          <span className="text-2xl font-bold">Sunday, October 27, 2024</span>
        </div>
        <div className="space-x-2">
          <Button variant="outline">Previous Day</Button>
          <Button variant="outline">Next Day</Button>
        </div>
      </div>

      {/* Rest of your dashboard content */}
    </div>
  );
}