'use client';

import React, { useEffect, useState } from 'react';
import apis from '@/utils/apis';
import dayjs from 'dayjs';
import { currency as defaultCurrency } from '@/lib/utils';
import { useGlobalContext } from '@/context/Provider';

interface PayoutSummaryProps {
  summaryData?: any;
  gradientFrom?: string;
  gradientVia?: string;
  gradientTo?: string;
  highlightColorStart?: string;
  highlightColorEnd?: string;
}

const PayoutSummary: React.FC<PayoutSummaryProps> = ({
  summaryData,
  gradientFrom = 'var(--primary-brand, var(--orange-500))',
  gradientVia = 'var(--orange-400)',
  gradientTo = 'var(--orange-200)',
  highlightColorStart = 'var(--orange-100)',
  highlightColorEnd = 'var(--orange-50)',
}) => {
  const [data, setData] = useState<any>(summaryData || null);
  const [loading, setLoading] = useState<boolean>(!summaryData);
  const context = useGlobalContext?.();
  const userInfo = context?.userInfo;
  const activeCurrency = defaultCurrency;

  useEffect(() => {
    if (summaryData) {
      const payload = summaryData?.data && typeof summaryData.data === 'object' ? summaryData.data : summaryData;
      setData(payload);
      setLoading(false);
      return;
    }

    const fetchSummary = async () => {
      setLoading(true);
      try {
        const res: any = await apis.Report.getSummary();
        const payload = res?.data && typeof res.data === 'object' ? res.data : res;
        setData(payload);
      } catch (error) {
        console.error('Error fetching payout summary:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchSummary();
  }, [summaryData]);

  const formatCurrency = (val: any) => {
    const num = Number(val) || 0;
    return `${activeCurrency}${num.toLocaleString('en-IN', { maximumFractionDigits: 2 })}`;
  };

  const formatDate = (dateStr: any) => {
    if (!dateStr) return 'N/A';
    const d = dayjs(dateStr);
    return d.isValid() ? d.format('D MMMM, YYYY') : 'N/A';
  };

  const todayEarning = data?.revenue?.today_earning ?? data?.today_earning ?? 0;
  const netEarning = data?.revenue?.overall_earning ?? data?.overall_earning ?? 0;
  const platformCommission = data?.platform_commission ?? 0;
  const pendingSettlement = data?.pending_settlement ?? data?.pending_payout ?? 0;
  const lastSettlementDate = data?.last_payout_date ?? data?.last_payout_created_at;

  return (
    <div className="w-full bg-white rounded-2xl p-6 border border-gray-100 shadow-sm flex flex-col justify-between h-[440px]">
      <div>
        <h3 className="text-base font-bold text-gray-900">Payout Summary</h3>

        {/* Dynamic Gradient Banner */}
        <div
          className="relative w-full h-[145px] rounded-2xl p-5 text-white flex flex-col justify-between overflow-hidden my-4 shadow-sm select-none"
          style={{
            background: `linear-gradient(135deg, ${gradientFrom}, ${gradientVia}, ${gradientTo})`,
          }}
        >
          {/* Ambient Glow Circles */}
          <div className="absolute -top-12 -right-12 w-48 h-48 bg-white/10 rounded-full blur-2xl pointer-events-none" />
          <div className="absolute -bottom-10 right-28 w-36 h-36 bg-white/15 rounded-full blur-xl pointer-events-none" />

          {loading ? (
            <div className="flex-1 flex items-center justify-center">
              <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
            </div>
          ) : (
            <>
              <div className="relative z-10">
                <p className="text-xs font-medium text-white/90">Today's Earnings</p>
                <h3 className="text-2xl font-bold mt-1 text-white tracking-tight">{formatCurrency(todayEarning)}</h3>
              </div>

              <div className="relative z-10 flex items-center gap-1.5 text-xs font-bold text-emerald-700 bg-white/95 backdrop-blur-md w-fit px-2.5 py-1 rounded-full shadow-xs">
                <span className="text-emerald-600 font-extrabold">↗</span>
                <span>2% vs yesterday</span>
              </div>

              {/* Pure SVG 3D Bar Chart Graphic */}
              <div className="absolute right-2 bottom-0 w-[175px] h-[135px] pointer-events-none z-0 flex items-end justify-end">
                <svg viewBox="0 0 180 140" className="w-full h-full overflow-visible">
                  <defs>
                    <linearGradient id="barGrad1" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stopColor={gradientFrom} />
                      <stop offset="100%" stopColor={gradientVia} />
                    </linearGradient>
                    <linearGradient id="barGrad2" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stopColor={gradientVia} />
                      <stop offset="100%" stopColor={gradientTo} />
                    </linearGradient>
                    <linearGradient id="barGrad3" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stopColor={gradientTo} />
                      <stop offset="100%" stopColor="var(--orange-300)" />
                    </linearGradient>
                    <linearGradient id="barGradCyan" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stopColor={highlightColorStart} />
                      <stop offset="100%" stopColor={highlightColorEnd} />
                    </linearGradient>
                    <linearGradient id="arrowGrad" x1="0%" y1="0%" x2="100%" y2="0%">
                      <stop offset="0%" stopColor="var(--orange-100)" />
                      <stop offset="100%" stopColor="var(--orange-50)" />
                    </linearGradient>

                    <filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
                      <feGaussianBlur stdDeviation="3" result="blur" />
                      <feComposite in="SourceGraphic" in2="blur" operator="over" />
                    </filter>
                    <filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
                      <feDropShadow dx="0" dy="4" stdDeviation="3" floodColor="#000" floodOpacity="0.2" />
                    </filter>
                  </defs>

                  {/* 3D Bar 1 */}
                  <g filter="url(#shadow)">
                    <rect x="15" y="85" width="28" height="45" rx="5" fill="url(#barGrad1)" />
                    <ellipse cx="29" cy="85" rx="14" ry="4" fill="var(--orange-200)" opacity="0.6" />
                  </g>

                  {/* 3D Bar 2 */}
                  <g filter="url(#shadow)">
                    <rect x="52" y="65" width="28" height="65" rx="5" fill="url(#barGrad2)" />
                    <ellipse cx="66" cy="65" rx="14" ry="4" fill="var(--orange-100)" opacity="0.6" />
                  </g>

                  {/* 3D Bar 3 */}
                  <g filter="url(#shadow)">
                    <rect x="89" y="48" width="28" height="82" rx="5" fill="url(#barGrad3)" />
                    <ellipse cx="103" cy="48" rx="14" ry="4" fill="var(--orange-50)" opacity="0.6" />
                  </g>

                  {/* 3D Bar 4 (Highlighted Bar) */}
                  <g filter="url(#shadow)">
                    <rect x="126" y="22" width="30" height="108" rx="6" fill="url(#barGradCyan)" />
                    <ellipse cx="141" cy="22" rx="15" ry="4" fill="white" opacity="0.9" />
                  </g>

                  {/* Upward Growth Arrow Curve */}
                  <path
                    d="M 10 92 C 55 82, 90 62, 148 18"
                    fill="none"
                    stroke="url(#arrowGrad)"
                    strokeWidth="5"
                    strokeLinecap="round"
                    filter="url(#glow)"
                  />
                  {/* Arrowhead */}
                  <path
                    d="M 132 16 L 152 14 L 148 34"
                    fill="none"
                    stroke="url(#arrowGrad)"
                    strokeWidth="5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    filter="url(#glow)"
                  />
                </svg>
              </div>
            </>
          )}
        </div>

        {/* 2x2 Metric Grid */}
        <div className="grid grid-cols-2 gap-3 mt-4">
          <div className="bg-gray-50/70 border border-gray-100 rounded-xl p-3.5 space-y-1">
            <p className="text-[11px] text-gray-500 font-medium">Net Earnings</p>
            <p className="text-sm font-bold text-gray-900">{loading ? '...' : formatCurrency(netEarning)}</p>
          </div>

          <div className="bg-gray-50/70 border border-gray-100 rounded-xl p-3.5 space-y-1">
            <p className="text-[11px] text-gray-500 font-medium">Platform Commission</p>
            <p className="text-sm font-bold text-gray-900">{loading ? '...' : formatCurrency(platformCommission)}</p>
          </div>

          <div className="bg-gray-50/70 border border-gray-100 rounded-xl p-3.5 space-y-1">
            <p className="text-[11px] text-gray-500 font-medium">Pending Settlement</p>
            <p className="text-sm font-bold text-gray-900">{loading ? '...' : formatCurrency(pendingSettlement)}</p>
          </div>

          <div className="bg-gray-50/70 border border-gray-100 rounded-xl p-3.5 space-y-1">
            <p className="text-[11px] text-gray-500 font-medium">Last Settlement Date</p>
            <p className="text-sm font-bold text-gray-900">{loading ? '...' : formatDate(lastSettlementDate)}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PayoutSummary;
