'use client';

import { useState, useMemo } from 'react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';
import { useI18n } from '@/lib/i18n/context';

type MonthData = { month: string; orders: number };

interface OrdersChartProps {
  chartData: Record<string, MonthData[]>;
  years: string[];
  loading?: boolean;
}

export default function OrdersChart({ chartData, years, loading }: OrdersChartProps) {
  const { t, isRtl } = useI18n();
  const currentYear = years[0] ?? String(new Date().getFullYear());
  const [selectedYear, setSelectedYear] = useState<string>(currentYear);
  const [dropdownOpen, setDropdownOpen] = useState<boolean>(false);

  const data: MonthData[] = useMemo(() => {
    const raw = chartData[selectedYear] ?? [];
    /** في RTL عرض الشهور من ديسمبر → يناير يميناً لليسار كما في التصميم */
    return isRtl ? [...raw].reverse() : raw;
  }, [chartData, selectedYear, isRtl]);

  const dropdownAlign = isRtl ? 'right-0' : 'left-0';
  const itemAlign = isRtl ? 'text-right' : 'text-left';

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 sm:p-6 mb-6">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-bold text-gray-900">{t('ordersChart.title')}</h2>
        {years.length > 0 && (
          <div className="relative">
            <button
              type="button"
              onClick={() => setDropdownOpen(!dropdownOpen)}
              className="flex items-center gap-2 bg-gray-50 hover:bg-gray-100 border border-gray-200 px-4 py-2 rounded-lg cursor-pointer transition-colors whitespace-nowrap"
            >
              <i className="ri-calendar-line text-gray-500"></i>
              <span className="text-sm font-semibold text-gray-700">{selectedYear}</span>
              <i className={`ri-arrow-down-s-line text-gray-500 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`}></i>
            </button>
            {dropdownOpen && (
              <div
                className={`absolute ${dropdownAlign} top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-10 min-w-[120px] overflow-hidden`}
              >
                {years.map((year) => (
                  <button
                    key={year}
                    type="button"
                    onClick={() => {
                      setSelectedYear(year);
                      setDropdownOpen(false);
                    }}
                    className={`w-full ${itemAlign} px-4 py-2.5 text-sm cursor-pointer transition-colors whitespace-nowrap ${
                      selectedYear === year ? 'bg-blue-50 text-blue-600 font-semibold' : 'text-gray-700 hover:bg-gray-50'
                    }`}
                  >
                    {year}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      <div className="h-72">
        {loading ? (
          <div className="h-full bg-gray-100 rounded-lg animate-pulse" />
        ) : (
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={data} margin={{ top: 5, right: 10, left: 10, bottom: 5 }}>
              <defs>
                <linearGradient id="colorOrders" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3B82F6" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="#3B82F6" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="month" tick={{ fontSize: 12, fill: '#6B7280' }} axisLine={{ stroke: '#E5E7EB' }} tickLine={false} />
              <YAxis
                tick={{ fontSize: 12, fill: '#6B7280' }}
                axisLine={{ stroke: '#E5E7EB' }}
                tickLine={false}
                orientation={isRtl ? 'right' : 'left'}
              />
              <Tooltip
                contentStyle={{
                  backgroundColor: '#1F2937',
                  border: 'none',
                  borderRadius: '8px',
                  color: '#fff',
                  fontSize: '13px',
                  fontFamily: "'Expo Arabic', sans-serif",
                }}
                labelStyle={{ color: '#9CA3AF', marginBottom: '4px' }}
                formatter={(value: number | string) => [
                  `${value} ${t('ordersChart.tooltipOrdersUnit')}`,
                  t('ordersChart.tooltipSeriesName'),
                ]}
              />
              <Area
                type="monotone"
                dataKey="orders"
                stroke="#3B82F6"
                strokeWidth={2.5}
                fill="url(#colorOrders)"
                dot={{ r: 4, fill: '#3B82F6', stroke: '#fff', strokeWidth: 2 }}
                activeDot={{ r: 6, fill: '#3B82F6', stroke: '#fff', strokeWidth: 2 }}
              />
            </AreaChart>
          </ResponsiveContainer>
        )}
      </div>
    </div>
  );
}
