import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, Calendar } from 'lucide-react';

interface EarningsData {
  date: string;
  amount: number;
  orders: number;
}

interface EarningsChartProps {
  data: EarningsData[];
  period?: '7d' | '30d' | '90d';
  onPeriodChange?: (period: '7d' | '30d' | '90d') => void;
}

export default function EarningsChart({ 
  data, 
  period = '30d',
  onPeriodChange 
}: EarningsChartProps) {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  
  const totalEarnings = data.reduce((sum, d) => sum + d.amount, 0);
  const totalOrders = data.reduce((sum, d) => sum + d.orders, 0);
  const avgOrderValue = totalOrders > 0 ? totalEarnings / totalOrders : 0;
  
  // Calculate previous period for comparison
  const previousPeriodEarnings = totalEarnings * 0.85; // Mock previous period
  const earningsChange = ((totalEarnings - previousPeriodEarnings) / previousPeriodEarnings) * 100;

  const maxAmount = Math.max(...data.map(d => d.amount));
  const chartHeight = 200;
  const chartWidth = 100;

  const formatCurrency = (amount: number) => {
    if (amount >= 1000000) {
      return `฿${(amount / 1000000).toFixed(1)}M`;
    }
    if (amount >= 1000) {
      return `฿${(amount / 1000).toFixed(1)}K`;
    }
    return `฿${amount.toLocaleString()}`;
  };

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('th-TH', { day: 'numeric', month: 'short' });
  };

  return (
    <div className="bg-white rounded-xl border p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h3 className="font-medium text-lg">รายได้</h3>
        <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
          {(['7d', '30d', '90d'] as const).map(p => (
            <button
              key={p}
              onClick={() => onPeriodChange?.(p)}
              className={`px-3 py-1 text-sm rounded-md transition-colors ${
                period === p 
                  ? 'bg-white shadow-sm text-gray-900' 
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {p === '7d' ? '7 วัน' : p === '30d' ? '30 วัน' : '90 วัน'}
            </button>
          ))}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-3 gap-4">
        <div className="p-4 bg-blue-50 rounded-lg">
          <p className="text-sm text-gray-500">รายได้รวม</p>
          <p className="text-xl font-bold text-gray-900 mt-1">
            {formatCurrency(totalEarnings)}
          </p>
          <div className={`flex items-center gap-1 mt-1 text-sm ${
            earningsChange >= 0 ? 'text-green-600' : 'text-red-600'
          }`}>
            {earningsChange >= 0 ? (
              <TrendingUp className="w-4 h-4" />
            ) : (
              <TrendingDown className="w-4 h-4" />
            )}
            <span>{Math.abs(earningsChange).toFixed(1)}%</span>
          </div>
        </div>
        <div className="p-4 bg-green-50 rounded-lg">
          <p className="text-sm text-gray-500">คำสั่งซื้อ</p>
          <p className="text-xl font-bold text-gray-900 mt-1">
            {totalOrders.toLocaleString()}
          </p>
          <p className="text-xs text-gray-500 mt-1">คำสั่งซื้อทั้งหมด</p>
        </div>
        <div className="p-4 bg-purple-50 rounded-lg">
          <p className="text-sm text-gray-500">เฉลี่ย/คำสั่งซื้อ</p>
          <p className="text-xl font-bold text-gray-900 mt-1">
            {formatCurrency(avgOrderValue)}
          </p>
          <p className="text-xs text-gray-500 mt-1">AOV</p>
        </div>
      </div>

      {/* Chart */}
      <div className="relative">
        <div className="flex items-end justify-between h-[200px] gap-1">
          {data.map((d, i) => {
            const heightPercent = (d.amount / maxAmount) * 100;
            const isHovered = hoveredIndex === i;
            
            return (
              <div
                key={i}
                className="flex-1 relative group"
                onMouseEnter={() => setHoveredIndex(i)}
                onMouseLeave={() => setHoveredIndex(null)}
              >
                <div
                  className={`
                    bg-gradient-to-t from-blue-600 to-blue-400 rounded-t-md transition-all duration-200
                    ${isHovered ? 'bg-blue-600' : ''}
                  `}
                  style={{ 
                    height: `${heightPercent}%`,
                    minHeight: heightPercent > 0 ? '4px' : '0'
                  }}
                />
                
                {/* Tooltip */}
                {isHovered && (
                  <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 z-10">
                    <div className="bg-gray-900 text-white text-xs rounded-lg px-3 py-2 whitespace-nowrap">
                      <p className="font-medium">{formatCurrency(d.amount)}</p>
                      <p className="text-gray-400">{d.orders} คำสั่ง</p>
                      <p className="text-gray-500 text-[10px]">{formatDate(d.date)}</p>
                    </div>
                    <div className="w-2 h-2 bg-gray-900 rotate-45 absolute left-1/2 -translate-x-1/2 -bottom-1" />
                  </div>
                )}
              </div>
            );
          })}
        </div>
        
        {/* X-axis labels */}
        <div className="flex justify-between mt-2 text-xs text-gray-400">
          {data.length > 0 && (
            <>
              <span>{formatDate(data[0].date)}</span>
              {data.length > 1 && (
                <span>{formatDate(data[data.length - 1].date)}</span>
              )}
            </>
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between text-sm text-gray-500 pt-4 border-t">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <div className="w-3 h-3 bg-blue-500 rounded" />
            <span>รายได้</span>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <Calendar className="w-4 h-4" />
          <span>อัปเดตเมื่อ {new Date().toLocaleDateString('th-TH')}</span>
        </div>
      </div>
    </div>
  );
}
