'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { 
  AreaChart, 
  Area, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer 
} from 'recharts'
import { BarChart3, TrendingUp } from 'lucide-react'

type ChartData = {
  name: string // e.g. "Mon", "Jan", "2023"
  orders: number
  revenue: number
}

interface DashboardChartsProps {
  data: ChartData[]
  title?: string
}

export function DashboardCharts({ data, title = "Transaction Overview" }: DashboardChartsProps) {
  const [metric, setMetric] = useState<'revenue' | 'orders'>('revenue')

  const formatYAxis = (value: number) => {
    if (metric === 'revenue') {
      if (value >= 1000000) return `Rp ${(value / 1000000).toFixed(1)}M`
      if (value >= 1000) return `Rp ${(value / 1000).toFixed(1)}K`
      return `Rp ${value}`
    }
    return value.toString()
  }

  const formatTooltip = (value: number) => {
    if (metric === 'revenue') {
      return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(value)
    }
    return [value, 'Orders']
  }

  const [mounted, setMounted] = useState(false)
  
  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) {
    return (
      <Card className="shadow-sm border-border">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <div className="space-y-1">
            <CardTitle className="text-xl flex items-center">
              {metric === 'revenue' ? <TrendingUp className="mr-2 h-5 w-5 text-primary" /> : <BarChart3 className="mr-2 h-5 w-5 text-primary" />}
              {title}
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <div className="h-[300px] flex items-center justify-center text-muted-foreground">
            Loading chart...
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="shadow-sm border-border">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <div className="space-y-1">
          <CardTitle className="text-xl flex items-center">
            {metric === 'revenue' ? <TrendingUp className="mr-2 h-5 w-5 text-primary" /> : <BarChart3 className="mr-2 h-5 w-5 text-primary" />}
            {title}
          </CardTitle>
          <CardDescription>
            Viewing {metric === 'revenue' ? 'total revenue' : 'number of orders'} over time.
          </CardDescription>
        </div>
        <div className="flex bg-muted p-1 rounded-md">
          <Button 
            variant={metric === 'revenue' ? 'default' : 'ghost'} 
            size="sm" 
            className="h-7 px-3 text-xs"
            onClick={() => setMetric('revenue')}
          >
            Revenue
          </Button>
          <Button 
            variant={metric === 'orders' ? 'default' : 'ghost'} 
            size="sm" 
            className="h-7 px-3 text-xs"
            onClick={() => setMetric('orders')}
          >
            Orders
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {data.length === 0 ? (
          <div className="h-[300px] flex items-center justify-center text-muted-foreground">
            No data available for this period.
          </div>
        ) : (
          <div className="h-[300px] w-full mt-4">
            <ResponsiveContainer width="100%" height="100%" minWidth={0} minHeight={0}>
              <AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                <defs>
                  <linearGradient id="colorMetric" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="var(--color-primary)" stopOpacity={0.3}/>
                    <stop offset="95%" stopColor="var(--color-primary)" stopOpacity={0}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--color-border)" opacity={0.5} />
                <XAxis 
                  dataKey="name" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }} 
                  dy={10}
                />
                <YAxis 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }} 
                  tickFormatter={formatYAxis}
                  width={80}
                />
                <Tooltip 
                  contentStyle={{ borderRadius: '8px', border: '1px solid var(--color-border)', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                  formatter={formatTooltip as any}
                  labelStyle={{ fontWeight: 'bold', color: 'var(--color-foreground)', marginBottom: '4px' }}
                />
                <Area 
                  type="monotone" 
                  dataKey={metric} 
                  stroke="var(--color-primary)" 
                  strokeWidth={2}
                  fillOpacity={1} 
                  fill="url(#colorMetric)" 
                  animationDuration={1000}
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

