'use client';

import React, { useEffect, useState, useCallback } from 'react';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { Utensils } from 'lucide-react';
import { useGlobalContext } from '@/context/Provider';
import { currency } from '@/lib/utils';

dayjs.extend(utc);
dayjs.extend(timezone);

interface ProductItem {
  rank: number;
  food_id: string;
  name: string;
  image?: string;
  images?: string[];
  price: number;
  units_sold: number;
  total_revenue: number;
  formatted_revenue?: string;
  formatted_sold?: string;
}

const ItemAnalytics = () => {
  const [topProducts, setTopProducts] = useState<ProductItem[]>([]);
  const [lowestProducts, setLowestProducts] = useState<ProductItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { Toast } = useGlobalContext();

  const fetchItemAnalytics = useCallback(async () => {
    setLoading(true);
    try {
      const query = `limit=5&page=1`;
      const res: any = await apis.Report.getItemAnalytics(query);
      const data = res?.data ?? res;

      if (data) {
        setTopProducts(data.top_selling_products || []);
        setLowestProducts(data.lowest_selling_products || []);
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchItemAnalytics();
  }, [fetchItemAnalytics]);

  const getImageUrl = (item: ProductItem) => {
    const raw = item.image || item.images?.[0];
    if (!raw) return null;
    if (raw.startsWith('http://') || raw.startsWith('https://')) return raw;
    return `${BUCKET_ROOT}${raw}`;
  };

  // Find max units for proportional progress bar rendering
  const maxTopUnits = Math.max(...topProducts.map((p) => p.units_sold || 0), 1);
  const maxLowestUnits = Math.max(...lowestProducts.map((p) => p.units_sold || 0), 1);

  return (
    <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* CARD 1: TOP SELLING PRODUCTS */}
      <div className="w-full bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm flex flex-col">
        {/* Header */}
        <div className="pb-4 border-b border-gray-100 mb-4">
          <h3 className="text-base font-bold text-gray-900">Top Selling Products</h3>
        </div>

        {/* List Content */}
        {loading ? (
          <div className="h-48 flex items-center justify-center">
            <div className="w-6 h-6 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : topProducts.length === 0 ? (
          <div className="h-48 flex flex-col items-center justify-center text-xs text-gray-400">
            No top selling products found
          </div>
        ) : (
          <div className="space-y-4">
            {topProducts.map((item, idx) => {
              const imgUrl = getImageUrl(item);
              const pct = Math.max(10, Math.min(100, (item.units_sold / maxTopUnits) * 100));
              const rankNum = item.rank || idx + 1;

              return (
                <div key={item.food_id || idx} className="flex items-center gap-3">
                  <span className="text-xs font-bold text-gray-800 w-5 text-center">
                    #{rankNum}
                  </span>
                  <div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden flex-shrink-0 border border-gray-100 flex items-center justify-center">
                    {imgUrl ? (
                      <img
                        src={imgUrl}
                        alt={item.name}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                        }}
                      />
                    ) : (
                      <Utensils size={18} className="text-gray-400" />
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <h4 className="text-xs font-bold text-gray-900 truncate mb-1">
                      {item.name}
                    </h4>
                    {/* Green Bar */}
                    <div className="w-full bg-gray-100 h-2 rounded-full overflow-hidden">
                      <div
                        className="bg-emerald-500 h-full rounded-full transition-all duration-300"
                        style={{ width: `${pct}%` }}
                      />
                    </div>
                  </div>
                  <div className="text-right flex-shrink-0 pl-2">
                    <div className="text-xs font-bold text-gray-900">
                      {item.formatted_revenue || `${currency}${item.total_revenue || 0}`}
                    </div>
                    <div className="text-[11px] font-medium text-gray-400 mt-0.5">
                      {item.formatted_sold || `${item.units_sold || 0} Sold`}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* CARD 2: LOWEST SELLING PRODUCTS */}
      <div className="w-full bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm flex flex-col">
        {/* Header */}
        <div className="pb-4 border-b border-gray-100 mb-4">
          <h3 className="text-base font-bold text-gray-900">Lowest Selling Products</h3>
        </div>

        {/* List Content */}
        {loading ? (
          <div className="h-48 flex items-center justify-center">
            <div className="w-6 h-6 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : lowestProducts.length === 0 ? (
          <div className="h-48 flex flex-col items-center justify-center text-xs text-gray-400">
            No lowest selling products found
          </div>
        ) : (
          <div className="space-y-4">
            {lowestProducts.map((item, idx) => {
              const imgUrl = getImageUrl(item);
              const pct = Math.max(10, Math.min(100, (item.units_sold / maxLowestUnits) * 100));
              const rankNum = item.rank || idx + 1;

              return (
                <div key={item.food_id || idx} className="flex items-center gap-3">
                  <span className="text-xs font-bold text-gray-800 w-5 text-center">
                    #{rankNum}
                  </span>
                  <div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden flex-shrink-0 border border-gray-100 flex items-center justify-center">
                    {imgUrl ? (
                      <img
                        src={imgUrl}
                        alt={item.name}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                        }}
                      />
                    ) : (
                      <Utensils size={18} className="text-gray-400" />
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <h4 className="text-xs font-bold text-gray-900 truncate mb-1">
                      {item.name}
                    </h4>
                    {/* Red Bar */}
                    <div className="w-full bg-gray-100 h-2 rounded-full overflow-hidden">
                      <div
                        className="bg-rose-500 h-full rounded-full transition-all duration-300"
                        style={{ width: `${pct}%` }}
                      />
                    </div>
                  </div>
                  <div className="text-right flex-shrink-0 pl-2">
                    <div className="text-xs font-bold text-gray-900">
                      {item.formatted_revenue || `${currency}${item.total_revenue || 0}`}
                    </div>
                    <div className="text-[11px] font-medium text-gray-400 mt-0.5">
                      {item.formatted_sold || `${item.units_sold || 0} Sold`}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

export default ItemAnalytics;
