"use client"

import { useState, useEffect } from "react"
import {
  format,
  startOfMonth,
  endOfMonth,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  isSameMonth,
  isSameDay,
  addMonths,
  subMonths,
  setMonth,
  setYear,
  getYear,
  getMonth,
  parseISO,
} from "date-fns"
import { ChevronLeft, ChevronRight, TrendingUp, TrendingDown, Loader2 } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

interface TradeExecution {
  id: string
  action: string
  profitLoss: number | null
  executionDate: string
}

interface Trade {
  id: string
  createdAt: string
  instrument: string
  duration: number | null
  executions: TradeExecution[]
}

export function CalendarContent() {
  const [currentDate, setCurrentDate] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())
  const [trades, setTrades] = useState<Trade[]>([])
  const [loading, setLoading] = useState(false)

  const months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ]

  const years = Array.from({ length: 10 }, (_, i) => getYear(new Date()) - 5 + i)

  const fetchTrades = async (date: Date) => {
    setLoading(true)
    try {
      const start = startOfMonth(date)
      const end = endOfMonth(date)
      // Fetch a bit more to cover the calendar grid (start of week, end of week)
      const gridStart = startOfWeek(start)
      const gridEnd = endOfWeek(end)

      const params = new URLSearchParams({
        from: gridStart.toISOString(),
        to: gridEnd.toISOString()
      })

      const res = await fetch(`/api/user/trades?${params}`)
      if (!res.ok) throw new Error("Failed to fetch trades")
      const data = await res.json()
      setTrades(data.trades)
    } catch (error) {
      console.error(error)
      toast.error("Failed to load trades")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTrades(currentDate)
  }, [currentDate])

  const handleMonthChange = (value: string) => {
    setCurrentDate(setMonth(currentDate, months.indexOf(value)))
  }

  const handleYearChange = (value: string) => {
    setCurrentDate(setYear(currentDate, parseInt(value)))
  }

  const nextMonth = () => setCurrentDate(addMonths(currentDate, 1))
  const prevMonth = () => setCurrentDate(subMonths(currentDate, 1))

  const monthStart = startOfMonth(currentDate)
  const monthEnd = endOfMonth(monthStart)
  const startDate = startOfWeek(monthStart)
  const endDate = endOfWeek(monthEnd)

  const calendarDays = eachDayOfInterval({ start: startDate, end: endDate })

  const getTradeStart = (trade: Trade) => {
    if (trade.executions.length > 0) {
      const sorted = [...trade.executions].sort((a, b) => new Date(a.executionDate).getTime() - new Date(b.executionDate).getTime())
      return new Date(sorted[0].executionDate)
    }
    return new Date(trade.createdAt)
  }

  const getTradeProfit = (trade: Trade) => {
    return trade.executions.reduce((acc, exec) => acc + (exec.profitLoss || 0), 0)
  }

  const getTradesForDay = (date: Date) => {
    return trades.filter(trade => isSameDay(getTradeStart(trade), date))
  }

  const getDayProfit = (date: Date) => {
    const dayTrades = getTradesForDay(date)
    if (dayTrades.length === 0) return null
    return dayTrades.reduce((acc, trade) => acc + getTradeProfit(trade), 0)
  }

  const selectedTrades = getTradesForDay(selectedDate)

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Calendar</h1>
          {/* <p className="text-muted-foreground"></p> */}
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" size="icon" onClick={prevMonth}>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Select value={months[getMonth(currentDate)]} onValueChange={handleMonthChange}>
            <SelectTrigger className="w-35">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {months.map((month) => (
                <SelectItem key={month} value={month}>{month}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={getYear(currentDate).toString()} onValueChange={handleYearChange}>
            <SelectTrigger className="w-25">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {years.map((year) => (
                <SelectItem key={year} value={year.toString()}>{year}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="outline" size="icon" onClick={nextMonth}>
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-7 gap-px bg-muted rounded-lg overflow-hidden border relative">
        {loading && (
            <div className="absolute inset-0 bg-background/50 flex items-center justify-center z-20">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
        )}
        {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((day) => (
          <div key={day} className="bg-background p-2 text-center text-sm font-medium text-muted-foreground">
            {day}
          </div>
        ))}
        {calendarDays.map((day) => {
          const dayProfit = getDayProfit(day)
          const isSelected = isSameDay(day, selectedDate)
          const isCurrentMonth = isSameMonth(day, currentDate)
          const isToday = isSameDay(day, new Date())

          return (
            <div
              key={day.toString()}
              onClick={() => setSelectedDate(day)}
              className={cn(
                "bg-background min-h-25 p-2 cursor-pointer transition-colors hover:bg-muted/50 relative group",
                !isCurrentMonth && "bg-muted/10 text-muted-foreground",
                isSelected && "ring-2 ring-primary inset-0 z-10"
              )}
            >
              <div className="flex justify-between items-start">
                <span className={cn(
                  "text-sm font-medium h-7 w-7 flex items-center justify-center rounded-full",
                  isToday && "bg-primary text-primary-foreground"
                )}>
                  {format(day, 'd')}
                </span>
                {dayProfit !== null && (
                  <span className={cn(
                    "text-xs font-medium px-1.5 py-0.5 rounded",
                    dayProfit >= 0 ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
                  )}>
                    {dayProfit >= 0 ? '+' : ''}{dayProfit.toFixed(2)}
                  </span>
                )}
              </div>
              <div className="mt-2 flex gap-1 flex-wrap">
                 {getTradesForDay(day).map((trade, i) => {
                    const profit = getTradeProfit(trade)
                    return <div key={i} className={cn("h-1.5 w-1.5 rounded-full", profit >= 0 ? "bg-green-500" : "bg-red-500")} />
                 })}
              </div>
            </div>
          )
        })}
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            Trades for {format(selectedDate, 'MMMM do, yyyy')}
            <span className="text-sm font-normal text-muted-foreground ml-auto">
              {selectedTrades.length} trades
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {selectedTrades.length > 0 ? (
            <div className="space-y-4">
              {selectedTrades.map((trade) => {
                const profit = getTradeProfit(trade)
                const start = getTradeStart(trade)
                
                let duration = 0
                if (trade.duration !== null) {
                  duration = trade.duration
                } else if (trade.executions.length > 0) {
                  const sorted = [...trade.executions].sort((a, b) => new Date(a.executionDate).getTime() - new Date(b.executionDate).getTime())
                  const first = new Date(sorted[0].executionDate)
                  const last = new Date(sorted[sorted.length - 1].executionDate)
                  duration = (last.getTime() - first.getTime()) / 1000
                }

                const firstAction = trade.executions.length > 0 
                  ? [...trade.executions].sort((a, b) => new Date(a.executionDate).getTime() - new Date(b.executionDate).getTime())[0].action 
                  : 'UNKNOWN'

                return (
                <div key={trade.id} className="flex items-center justify-between p-4 border rounded-lg bg-card hover:bg-accent/50 transition-colors">
                  <div className="flex items-center gap-4">
                    <div className={cn(
                      "p-2 rounded-full",
                      profit >= 0 ? "bg-green-100 text-green-600 dark:bg-green-900/20" : "bg-red-100 text-red-600 dark:bg-red-900/20"
                    )}>
                      {profit >= 0 ? <TrendingUp className="h-4 w-4" /> : <TrendingDown className="h-4 w-4" />}
                    </div>
                    <div>
                      <div className="font-medium">{trade.instrument}</div>
                      <div className="text-sm text-muted-foreground">
                        {format(start, 'h:mm a')} • {firstAction} • {duration.toFixed(0)}s
                      </div>
                    </div>
                  </div>
                  <div className={cn(
                    "font-semibold",
                    profit >= 0 ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"
                  )}>
                    {profit >= 0 ? '+' : ''}{profit.toFixed(2)}
                  </div>
                </div>
              )})}
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              No trades recorded for this day.
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
