'use client';

import { useEffect, useState } from 'react';
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Cell,
} from 'recharts';

interface BotData {
  name: string;
  conversations: number;
  color: string;
}

function CustomTooltip({
  active,
  payload,
}: {
  active?: boolean;
  payload?: Array<{ payload: BotData; value: number }>;
}) {
  if (!active || !payload || !payload[0]) return null;
  const d = payload[0].payload;

  return (
    <div className="rounded-lg border border-slate-700/60 bg-[#1a2332]/95 px-4 py-3 shadow-xl backdrop-blur-sm">
      <p className="text-sm font-semibold text-white mb-1">{d.name}</p>
      <div className="flex items-center gap-2 text-sm">
        <div className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: d.color }} />
        <span className="text-slate-300">Conversations:</span>
        <span className="font-semibold text-white">{d.conversations.toLocaleString()}</span>
      </div>
    </div>
  );
}

export default function BotsBarChart() {
  const [data, setData] = useState<BotData[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/analytics/bots')
      .then((r) => r.json())
      .then((d) => setData(d.bots || []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="rounded-xl border border-slate-700/40 bg-[#0f1729]/80 p-6">
      <div className="mb-6">
        <h3 className="text-base font-semibold text-white">Conversations by Bot</h3>
        <p className="text-xs text-slate-500 mt-0.5">Total conversations handled per bot</p>
      </div>

      {loading ? (
        <div className="h-[300px] flex items-center justify-center">
          <div className="h-8 w-8 border-2 border-cyan-500/30 border-t-cyan-500 rounded-full animate-spin" />
        </div>
      ) : (
        <div className="h-[300px]">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={data}
              layout="vertical"
              margin={{ top: 5, right: 40, left: 10, bottom: 5 }}
              barCategoryGap="20%"
            >
              <CartesianGrid
                strokeDasharray="3 3"
                stroke="#334155"
                strokeOpacity={0.3}
                horizontal={false}
              />
              <XAxis
                type="number"
                tick={{ fill: '#94a3b8', fontSize: 11 }}
                stroke="#334155"
                tickLine={false}
                axisLine={false}
              />
              <YAxis
                type="category"
                dataKey="name"
                tick={{ fill: '#cbd5e1', fontSize: 12 }}
                stroke="#334155"
                tickLine={false}
                axisLine={false}
                width={130}
              />
              <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(148,163,184,0.05)' }} />
              <Bar dataKey="conversations" radius={[0, 6, 6, 0]} barSize={28}>
                {data.map((entry, index) => (
                  <Cell key={index} fill={entry.color} fillOpacity={0.85} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
}
