'use client';
import { useEffect, useState } from 'react';
import { adminService } from '@/services/admin.service';
import type { AnalyticsData } from '@/types/admin.types';

const HEIGHT_CLASSES = ['h-[10%]', 'h-[20%]', 'h-[30%]', 'h-[40%]', 'h-[50%]', 'h-[60%]', 'h-[70%]', 'h-[80%]', 'h-[90%]', 'h-[100%]'] as const;

function getHeightClass(value: number): string {
  const idx = Math.min(HEIGHT_CLASSES.length - 1, Math.max(0, Math.round(value / 10) - 1));
  return HEIGHT_CLASSES[idx];
}

export default function AdminAnalyticsPage() {
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminService.getAnalytics().then((res) => {
      setData(res);
      setLoading(false);
    });
  }, []);

  if (loading) return <div className="animate-pulse space-y-4">{[1, 2, 3].map((i) => <div key={i} className="h-48 rounded-xl bg-white/[0.03]" />)}</div>;
  if (!data) return <p className="text-center text-slate-500 py-10">Failed to load analytics</p>;

  const orderStats = data.orderStats;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Analytics</h1>
          <p className="mt-1 text-sm text-white/50">Platform analytics and metrics</p>
        </div>
      </div>

      {/* Order Statistics */}
      <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
        <h3 className="text-sm font-medium text-white mb-4">Order Statistics</h3>
        <div className="grid grid-cols-5 gap-4">
          <div className="text-center p-3 rounded-lg bg-white/5">
            <p className="text-2xl font-bold text-amber-400">{orderStats.pending}</p>
            <p className="text-xs text-slate-400 mt-1">Pending</p>
          </div>
          <div className="text-center p-3 rounded-lg bg-white/5">
            <p className="text-2xl font-bold text-blue-400">{orderStats.open}</p>
            <p className="text-xs text-slate-400 mt-1">Open</p>
          </div>
          <div className="text-center p-3 rounded-lg bg-white/5">
            <p className="text-2xl font-bold text-emerald-400">{orderStats.completed}</p>
            <p className="text-xs text-slate-400 mt-1">Completed</p>
          </div>
          <div className="text-center p-3 rounded-lg bg-white/5">
            <p className="text-2xl font-bold text-red-400">{orderStats.cancelled}</p>
            <p className="text-xs text-slate-400 mt-1">Cancelled</p>
          </div>
          <div className="text-center p-3 rounded-lg bg-white/5">
            <p className="text-2xl font-bold text-orange-400">{orderStats.disputed}</p>
            <p className="text-xs text-slate-400 mt-1">Disputed</p>
          </div>
        </div>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* User Growth */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">User Growth (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.userGrowth.map((point, i) => {
              const pct = Math.max(5, (point.count / Math.max(...data.userGrowth.map(p => p.count)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-indigo-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Trade Volume */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">Trade Volume (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.tradeVolume.map((point, i) => {
              const pct = Math.max(5, (point.volume / Math.max(...data.tradeVolume.map(p => p.volume)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-emerald-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Revenue */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">Revenue (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.revenueData.map((point, i) => {
              const pct = Math.max(5, (point.revenue / Math.max(...data.revenueData.map(p => p.revenue)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-amber-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Commission */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">Commission (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.commissionData.map((point, i) => {
              const pct = Math.max(5, (point.commission / Math.max(...data.commissionData.map(p => p.commission)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-purple-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Wallet Activity */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">Wallet Activity (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.walletActivity.map((point, i) => {
              const pct = Math.max(5, (point.volume / Math.max(...data.walletActivity.map(p => p.volume)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-cyan-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Referral Growth */}
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <h3 className="text-sm font-medium text-white mb-4">Referral Growth (Last 30 Days)</h3>
          <div className="h-48 flex items-end gap-1">
            {data.referralGrowth.map((point, i) => {
              const pct = Math.max(5, (point.count / Math.max(...data.referralGrowth.map(p => p.count)) * 100));
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className={`w-full bg-pink-500/20 rounded-t ${getHeightClass(pct)}`} />
                  <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* System Usage */}
      <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
        <h3 className="text-sm font-medium text-white mb-4">System Usage (Active Users / Day)</h3>
        <div className="h-48 flex items-end gap-1">
          {data.systemUsage.map((point, i) => {
            const pct = Math.max(5, (point.active_users / Math.max(...data.systemUsage.map(p => p.active_users)) * 100));
            return (
              <div key={i} className="flex-1 flex flex-col items-center gap-1">
                <div className={`w-full bg-indigo-500/20 rounded-t ${getHeightClass(pct)}`} />
                <span className="text-[8px] text-slate-500 rotate-45 origin-left whitespace-nowrap">{new Date(point.date).getDate()}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
