import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card';
import { TrendingUp } from 'lucide-react';

interface RevenueDataPoint {
    month: string;
    revenue: number;
}

interface RevenueChartProps {
    data: RevenueDataPoint[];
}

export function RevenueChart({ data }: RevenueChartProps) {
    const maxRevenue = Math.max(...data.map(d => d.revenue), 1);
    const minRevenue = Math.min(...data.map(d => d.revenue), 0);
    const range = maxRevenue - minRevenue;

    const getYPosition = (revenue: number) => {
        return 100 - ((revenue - minRevenue) / range) * 80; // 80% of height for data, 20% for padding
    };

    const points = data
        .map((d, i) => {
            const x = (i / (data.length - 1)) * 100;
            const y = getYPosition(d.revenue);
            return `${x},${y}`;
        })
        .join(' ');

    const areaPoints = `0,100 ${points} 100,100`;

    const formatCurrency = (value: number) => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0,
        }).format(value);
    };

    const totalRevenue = data.reduce((sum, d) => sum + d.revenue, 0);
    const avgRevenue = totalRevenue / data.length;
    const lastMonth = data[data.length - 1]?.revenue || 0;
    const previousMonth = data[data.length - 2]?.revenue || 0;
    const growth = previousMonth > 0 ? ((lastMonth - previousMonth) / previousMonth) * 100 : 0;

    return (
        <Card className="col-span-1 lg:col-span-2 border-0 shadow-sm hover:shadow-md transition-shadow">
            <CardHeader className="pb-4">
                <div className="flex items-center justify-between">
                    <div>
                        <CardTitle className="text-xl font-bold">Revenue Analytics</CardTitle>
                        <p className="text-sm text-gray-500 mt-1">Monthly recurring revenue trend</p>
                    </div>
                    <div className="text-right">
                        <p className="text-sm text-gray-600">Current MRR</p>
                        <p className="text-2xl font-bold text-gray-900">{formatCurrency(lastMonth)}</p>
                        <p className={`text-xs font-medium flex items-center gap-1 justify-end mt-1 ${growth >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                            <TrendingUp className="h-3 w-3" />
                            {growth >= 0 ? '+' : ''}{growth.toFixed(1)}% from last month
                        </p>
                    </div>
                </div>
            </CardHeader>
            <CardContent>
                <div className="relative h-64">
                    <svg className="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
                        {/* Grid lines */}
                        <line x1="0" y1="20" x2="100" y2="20" stroke="#e5e7eb" strokeWidth="0.2" />
                        <line x1="0" y1="40" x2="100" y2="40" stroke="#e5e7eb" strokeWidth="0.2" />
                        <line x1="0" y1="60" x2="100" y2="60" stroke="#e5e7eb" strokeWidth="0.2" />
                        <line x1="0" y1="80" x2="100" y2="80" stroke="#e5e7eb" strokeWidth="0.2" />

                        {/* Area fill */}
                        <polygon
                            points={areaPoints}
                            fill="url(#gradient)"
                            opacity="0.3"
                        />

                        {/* Line */}
                        <polyline
                            points={points}
                            fill="none"
                            stroke="#3b82f6"
                            strokeWidth="0.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                        />

                        {/* Data points */}
                        {data.map((d, i) => {
                            const x = (i / (data.length - 1)) * 100;
                            const y = getYPosition(d.revenue);
                            return (
                                <circle
                                    key={i}
                                    cx={x}
                                    cy={y}
                                    r="0.8"
                                    fill="#3b82f6"
                                    className="hover:r-1.5 transition-all"
                                />
                            );
                        })}

                        {/* Gradient definition */}
                        <defs>
                            <linearGradient id="gradient" x1="0%" y1="0%" x2="0%" y2="100%">
                                <stop offset="0%" stopColor="#3b82f6" stopOpacity="0.8" />
                                <stop offset="100%" stopColor="#3b82f6" stopOpacity="0.1" />
                            </linearGradient>
                        </defs>
                    </svg>
                </div>

                {/* Month labels */}
                <div className="flex justify-between mt-4 px-2">
                    {data.filter((_, i) => i % 2 === 0).map((d, i) => (
                        <span key={i} className="text-xs text-gray-500">
                            {d.month.split(' ')[0]}
                        </span>
                    ))}
                </div>

                {/* Summary stats */}
                <div className="grid grid-cols-3 gap-4 mt-6 pt-6 border-t">
                    <div>
                        <p className="text-xs text-gray-600">Total Revenue</p>
                        <p className="text-lg font-bold text-gray-900 mt-1">{formatCurrency(totalRevenue)}</p>
                    </div>
                    <div>
                        <p className="text-xs text-gray-600">Average MRR</p>
                        <p className="text-lg font-bold text-gray-900 mt-1">{formatCurrency(avgRevenue)}</p>
                    </div>
                    <div>
                        <p className="text-xs text-gray-600">Peak Month</p>
                        <p className="text-lg font-bold text-gray-900 mt-1">{formatCurrency(maxRevenue)}</p>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
