/**
 * OccupancyHeatmap Component
 * Heatmap de ocupação semanal dos horários
 * @version 1.0
 */

import { useMemo } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Cell,
} from "recharts";
import { Calendar, TrendingUp, TrendingDown } from "lucide-react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";

interface OccupancyData {
  date: string;
  total_slots: number;
  occupied_slots: number;
  available_slots: number;
  occupancy_rate: number;
}

interface OccupancyHeatmapProps {
  data: OccupancyData[];
  isLoading?: boolean;
  title?: string;
  className?: string;
}

export function OccupancyHeatmap({
  data,
  isLoading = false,
  title = "Ocupação Semanal",
  className = "",
}: OccupancyHeatmapProps) {
  // Transformar dados para formato do chart
  const chartData = useMemo(() => {
    return data.map((item) => ({
      date: format(new Date(item.date), "EEE dd/MM", { locale: ptBR }),
      fullDate: item.date,
      ocupados: item.occupied_slots,
      disponiveis: item.available_slots,
      taxa: item.occupancy_rate,
    }));
  }, [data]);

  // Calcular estatísticas
  const stats = useMemo(() => {
    if (data.length === 0) return null;

    const avgOccupancy =
      data.reduce((sum, item) => sum + item.occupancy_rate, 0) / data.length;

    const maxOccupancy = Math.max(...data.map((item) => item.occupancy_rate));
    const minOccupancy = Math.min(...data.map((item) => item.occupancy_rate));

    const totalSlots = data.reduce((sum, item) => sum + item.total_slots, 0);
    const totalOccupied = data.reduce(
      (sum, item) => sum + item.occupied_slots,
      0
    );

    // Tendência (comparar primeira metade com segunda metade)
    const mid = Math.floor(data.length / 2);
    const firstHalf =
      data.slice(0, mid).reduce((sum, item) => sum + item.occupancy_rate, 0) /
      mid;
    const secondHalf =
      data.slice(mid).reduce((sum, item) => sum + item.occupancy_rate, 0) /
      (data.length - mid);
    const trend = secondHalf - firstHalf;

    return {
      avgOccupancy: avgOccupancy.toFixed(1),
      maxOccupancy: maxOccupancy.toFixed(1),
      minOccupancy: minOccupancy.toFixed(1),
      totalSlots,
      totalOccupied,
      trend,
      trendText:
        trend > 5 ? "crescente" : trend < -5 ? "decrescente" : "estável",
    };
  }, [data]);

  // Cor baseada na taxa de ocupação
  const getOccupancyColor = (rate: number) => {
    if (rate >= 80) return "#dc2626"; // red-600 - crítico
    if (rate >= 60) return "#f59e0b"; // amber-500 - alto
    if (rate >= 40) return "#22c55e"; // green-500 - bom
    return "#3b82f6"; // blue-500 - baixo
  };

  // Tooltip customizado
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const CustomTooltip = ({
    active,
    payload,
  }: {
    active?: boolean;
    payload?: any[];
  }) => {
    if (!active || !payload || !payload.length) return null;

    const data = payload[0].payload;

    return (
      <div className="bg-white dark:bg-gray-800 p-3 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
        <p className="font-semibold text-gray-900 dark:text-gray-100 mb-2">
          {data.date}
        </p>
        <div className="space-y-1 text-sm">
          <p className="text-green-600 dark:text-green-400">
            ✓ Ocupados: {data.ocupados}
          </p>
          <p className="text-blue-600 dark:text-blue-400">
            ○ Disponíveis: {data.disponiveis}
          </p>
          <p className="text-gray-700 dark:text-gray-300 font-semibold mt-2">
            Taxa: {data.taxa.toFixed(1)}%
          </p>
        </div>
      </div>
    );
  };

  if (isLoading) {
    return (
      <div
        className={`bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm ${className}`}
      >
        <div className="animate-pulse">
          <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-4"></div>
          <div className="h-64 bg-gray-200 dark:bg-gray-700 rounded"></div>
        </div>
      </div>
    );
  }

  if (data.length === 0) {
    return (
      <div
        className={`bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm ${className}`}
      >
        <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
          {title}
        </h3>
        <div className="flex flex-col items-center justify-center py-12 text-gray-500 dark:text-gray-400">
          <Calendar className="w-12 h-12 mb-3 opacity-50" />
          <p>Nenhum dado de ocupação disponível</p>
          <p className="text-sm mt-1">
            Os dados aparecem assim que houver consultas agendadas
          </p>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm ${className}`}
    >
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            {title}
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Últimos 7 dias de ocupação
          </p>
        </div>

        {stats && (
          <div className="flex items-center gap-2 text-sm">
            {stats.trend > 5 ? (
              <TrendingUp className="w-4 h-4 text-green-600" />
            ) : stats.trend < -5 ? (
              <TrendingDown className="w-4 h-4 text-red-600" />
            ) : (
              <span className="w-4 h-4 text-gray-400">—</span>
            )}
            <span
              className={`font-medium ${
                stats.trend > 5
                  ? "text-green-600"
                  : stats.trend < -5
                  ? "text-red-600"
                  : "text-gray-600 dark:text-gray-400"
              }`}
            >
              {stats.trendText}
            </span>
          </div>
        )}
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3">
            <p className="text-xs text-blue-600 dark:text-blue-400 font-medium mb-1">
              Média
            </p>
            <p className="text-2xl font-bold text-blue-700 dark:text-blue-300">
              {stats.avgOccupancy}%
            </p>
          </div>
          <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-3">
            <p className="text-xs text-green-600 dark:text-green-400 font-medium mb-1">
              Máxima
            </p>
            <p className="text-2xl font-bold text-green-700 dark:text-green-300">
              {stats.maxOccupancy}%
            </p>
          </div>
          <div className="bg-purple-50 dark:bg-purple-900/20 rounded-lg p-3">
            <p className="text-xs text-purple-600 dark:text-purple-400 font-medium mb-1">
              Mínima
            </p>
            <p className="text-2xl font-bold text-purple-700 dark:text-purple-300">
              {stats.minOccupancy}%
            </p>
          </div>
          <div className="bg-orange-50 dark:bg-orange-900/20 rounded-lg p-3">
            <p className="text-xs text-orange-600 dark:text-orange-400 font-medium mb-1">
              Ocupados
            </p>
            <p className="text-2xl font-bold text-orange-700 dark:text-orange-300">
              {stats.totalOccupied}/{stats.totalSlots}
            </p>
          </div>
        </div>
      )}

      {/* Chart */}
      <ResponsiveContainer width="100%" height={300}>
        <BarChart data={chartData}>
          <CartesianGrid
            strokeDasharray="3 3"
            className="stroke-gray-200 dark:stroke-gray-700"
          />
          <XAxis
            dataKey="date"
            tick={{ fill: "currentColor" }}
            className="text-gray-600 dark:text-gray-400"
          />
          <YAxis
            tick={{ fill: "currentColor" }}
            className="text-gray-600 dark:text-gray-400"
          />
          <Tooltip content={<CustomTooltip />} />
          <Legend />
          <Bar
            dataKey="ocupados"
            fill="#22c55e"
            name="Ocupados"
            radius={[8, 8, 0, 0]}
          >
            {chartData.map((entry, index) => (
              <Cell
                key={`cell-${index}`}
                fill={getOccupancyColor(entry.taxa)}
              />
            ))}
          </Bar>
          <Bar
            dataKey="disponiveis"
            fill="#3b82f6"
            name="Disponíveis"
            radius={[8, 8, 0, 0]}
          />
        </BarChart>
      </ResponsiveContainer>

      {/* Legend */}
      <div className="flex items-center justify-center gap-6 mt-4 text-xs">
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded bg-blue-500"></div>
          <span className="text-gray-600 dark:text-gray-400">
            Baixo (&lt;40%)
          </span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded bg-green-500"></div>
          <span className="text-gray-600 dark:text-gray-400">Bom (40-60%)</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded bg-amber-500"></div>
          <span className="text-gray-600 dark:text-gray-400">
            Alto (60-80%)
          </span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded bg-red-600"></div>
          <span className="text-gray-600 dark:text-gray-400">
            Crítico (&gt;80%)
          </span>
        </div>
      </div>
    </div>
  );
}
