'use client'

import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { LeadStats } from '@/lib/db'

interface LeadsChartProps {
  stats: LeadStats
}

export default function LeadsChart({ stats }: LeadsChartProps) {
  // Fill in missing dates with 0 values for the last 30 days
  const fillMissingDates = (data: { date: string; count: number }[]) => {
    const filledData = []
    const today = new Date()
    
    for (let i = 29; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(date.getDate() - i)
      const dateStr = date.toISOString().split('T')[0] // YYYY-MM-DD format
      
      const existingData = data.find(d => d.date === dateStr)
      filledData.push({
        date: dateStr,
        count: existingData ? existingData.count : 0,
        formattedDate: date.toLocaleDateString('en-AU', { 
          month: 'short', 
          day: 'numeric' 
        })
      })
    }
    
    return filledData
  }

  const chartData = fillMissingDates(stats.by_date)

  return (
    <div className="dashboard-card p-chorus-lg mb-chorus-xxl">
      <h3 className="text-xl font-semibold text-carbon-900 dark:text-white mb-chorus-lg">
        Lead Trends (Last 30 Days)
      </h3>
      
      <div className="h-80">
        <ResponsiveContainer width="100%" height="100%">
          <LineChart
            data={chartData}
            margin={{
              top: 20,
              right: 30,
              left: 20,
              bottom: 20,
            }}
          >
            <CartesianGrid 
              strokeDasharray="3 3" 
              stroke="#e5e5e5" 
              className="opacity-30"
            />
            <XAxis 
              dataKey="formattedDate"
              stroke="#6b7280"
              fontSize={12}
              tick={{ fill: '#6b7280' }}
              interval="preserveStartEnd"
            />
            <YAxis 
              stroke="#6b7280"
              fontSize={12}
              tick={{ fill: '#6b7280' }}
              allowDecimals={false}
            />
            <Tooltip 
              contentStyle={{
                backgroundColor: '#ffffff',
                border: '1px solid #e5e7eb',
                borderRadius: '8px',
                boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)',
              }}
              labelStyle={{ color: '#374151', fontWeight: 'bold' }}
              itemStyle={{ color: '#8b5cf6' }}
              formatter={(value: number) => [value, 'Leads']}
              labelFormatter={(label: string) => `Date: ${label}`}
            />
            <Line 
              type="monotone" 
              dataKey="count" 
              stroke="#8b5cf6" 
              strokeWidth={3}
              dot={{ 
                fill: '#8b5cf6', 
                strokeWidth: 2, 
                r: 4 
              }}
              activeDot={{ 
                r: 6, 
                stroke: '#8b5cf6',
                strokeWidth: 2,
                fill: '#ffffff'
              }}
            />
          </LineChart>
        </ResponsiveContainer>
      </div>
      
      {chartData.length === 0 && (
        <div className="flex items-center justify-center h-80 text-carbon-500 dark:text-carbon-400">
          <p>No data available for the last 30 days</p>
        </div>
      )}
    </div>
  )
}