import { useMemo } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { useTimezone } from '../hooks/useTimezone';

interface DailyEntry {
  date: string;
  user_email: string;
  session_count: number;
}

interface ChartData {
  daily_activity: DailyEntry[];
}

function shortEmail(email: string): string {
  const at = email.indexOf('@');
  return at > 0 ? email.slice(0, at) : email;
}

const INTENSITY_COLORS = [
  'bg-surface-2',        // 0
  'bg-accent/20',        // low
  'bg-accent/40',        // medium-low
  'bg-accent/60',        // medium
  'bg-accent/80',        // medium-high
  'bg-accent',           // high
];

function getIntensityClass(count: number, max: number): string {
  if (count === 0) return INTENSITY_COLORS[0];
  const ratio = count / max;
  if (ratio < 0.15) return INTENSITY_COLORS[1];
  if (ratio < 0.3) return INTENSITY_COLORS[2];
  if (ratio < 0.5) return INTENSITY_COLORS[3];
  if (ratio < 0.75) return INTENSITY_COLORS[4];
  return INTENSITY_COLORS[5];
}

export default function DailyHeatmap() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', { daily_activity: [] });
  const { formatDate: fmtDate } = useTimezone();

  const { users, dates, grid, maxCount, totalByUser, totalByDate } = useMemo(() => {
    const entries = data.daily_activity || [];
    if (!entries.length) return { users: [], dates: [], grid: new Map(), maxCount: 0, totalByUser: new Map(), totalByDate: new Map() };

    const userSet = new Set<string>();
    const dateSet = new Set<string>();
    const grid = new Map<string, number>();
    const totalByUser = new Map<string, number>();
    const totalByDate = new Map<string, number>();
    let maxCount = 0;

    for (const e of entries) {
      userSet.add(e.user_email);
      dateSet.add(e.date);
      const key = `${e.user_email}|${e.date}`;
      grid.set(key, e.session_count);
      if (e.session_count > maxCount) maxCount = e.session_count;
      totalByUser.set(e.user_email, (totalByUser.get(e.user_email) || 0) + e.session_count);
      totalByDate.set(e.date, (totalByDate.get(e.date) || 0) + e.session_count);
    }

    const users = [...userSet].sort((a, b) => (totalByUser.get(b) || 0) - (totalByUser.get(a) || 0));
    const dates = [...dateSet].sort();

    return { users, dates, grid, maxCount, totalByUser, totalByDate };
  }, [data]);

  if (loading || !dates.length) return null;

  const formatDateLocal = (d: string) => fmtDate(d + 'T12:00:00Z');

  const busiest = [...totalByDate.entries()].sort((a, b) => b[1] - a[1])[0];

  return (
    <section className="px-8 max-w-7xl mx-auto py-20">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6 }}
      >
        <h2 className="text-3xl md:text-4xl font-bold mb-2">
          {busiest ? `${busiest[1]} sessions on ${formatDateLocal(busiest[0])}` : 'Daily Activity'} — your busiest day.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          A heatmap of AI session activity by developer and day. Darker cells mean more sessions.
          This reveals who's active when — and who's sprinting vs sustaining.
        </p>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ delay: 0.1, duration: 0.5 }}
        className="bg-surface-1 border border-border-dim rounded-xl p-6 overflow-x-auto"
      >
        <table className="w-full">
          <thead>
            <tr>
              <th className="text-left text-xs text-text-3 font-medium pb-3 pr-4 min-w-[140px]">Developer</th>
              {dates.map(d => (
                <th key={d} className="text-center text-[10px] text-text-3 font-medium pb-3 px-1 min-w-[72px]">
                  {formatDateLocal(d)}
                </th>
              ))}
              <th className="text-center text-xs text-text-3 font-medium pb-3 pl-4">Total</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user, ui) => (
              <motion.tr
                key={user}
                initial={{ opacity: 0, x: -10 }}
                whileInView={{ opacity: 1, x: 0 }}
                viewport={{ once: true }}
                transition={{ delay: ui * 0.05, duration: 0.3 }}
              >
                <td className="text-xs text-text-2 font-medium py-1.5 pr-4 truncate max-w-[160px]">
                  {shortEmail(user)}
                </td>
                {dates.map(d => {
                  const count = grid.get(`${user}|${d}`) || 0;
                  return (
                    <td key={d} className="px-1 py-1.5">
                      <div
                        className={`h-10 rounded-md flex items-center justify-center text-xs font-semibold transition-colors ${getIntensityClass(count, maxCount)} ${count > 0 ? 'text-text-1' : 'text-text-3/30'}`}
                        title={`${shortEmail(user)}: ${count} sessions on ${formatDateLocal(d)}`}
                      >
                        {count > 0 ? count : '·'}
                      </div>
                    </td>
                  );
                })}
                <td className="text-center text-sm font-bold text-text-1 pl-4">
                  {totalByUser.get(user) || 0}
                </td>
              </motion.tr>
            ))}
            {/* Totals row */}
            <tr className="border-t border-border-dim">
              <td className="text-xs text-text-3 font-semibold py-2 pr-4">Daily Total</td>
              {dates.map(d => (
                <td key={d} className="text-center text-xs text-text-2 font-semibold py-2 px-1">
                  {totalByDate.get(d) || 0}
                </td>
              ))}
              <td className="text-center text-sm font-bold text-accent pl-4">
                {[...totalByUser.values()].reduce((a, b) => a + b, 0)}
              </td>
            </tr>
          </tbody>
        </table>

        {/* Legend */}
        <div className="flex items-center gap-2 mt-4 justify-end">
          <span className="text-[10px] text-text-3">Less</span>
          {INTENSITY_COLORS.map((cls, i) => (
            <div key={i} className={`w-4 h-4 rounded-sm ${cls}`} />
          ))}
          <span className="text-[10px] text-text-3">More</span>
        </div>
      </motion.div>
    </section>
  );
}
