import { useMemo } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { useTimezone } from '../hooks/useTimezone';
import {
  Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Line, ComposedChart,
} from 'recharts';

interface HourlyEntry {
  hour: string;
  sessions: number;
  sessions_with_edits: number;
  edit_rate: number;
}

interface ChartData {
  hourly_productivity: HourlyEntry[];
}

const CustomTooltip = ({ active, payload }: any) => {
  if (!active || !payload?.length) return null;
  const d = payload[0]?.payload;
  return (
    <div className="bg-surface-3 border border-border-dim rounded-lg px-3 py-2 text-xs shadow-xl">
      <div className="text-text-2 mb-1">{d?.displayLabel}</div>
      <div className="text-text-1">{d?.sessions} sessions</div>
      <div className="text-green">{d?.sessions_with_edits} with edits ({d?.edit_rate?.toFixed(1)}%)</div>
    </div>
  );
};

export default function HourlyProductivity() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {
    hourly_productivity: [],
  });
  const { tz, formatHour } = useTimezone();

  const chartData = useMemo(() => {
    const hours = data.hourly_productivity || [];
    if (!hours.length) return [];
    return hours.map(h => {
      const utcHour = parseInt(h.hour, 10);
      return {
        ...h,
        hour_num: utcHour,
        displayHour: formatHour(utcHour),
        displayLabel: formatHour(utcHour) + ` ${tz}`,
      };
    }).sort((a, b) => a.hour_num - b.hour_num);
  }, [data, tz, formatHour]);

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

  const peakHour = chartData.reduce((a, b) => b.sessions > a.sessions ? b : a);
  const mostProductiveHour = chartData.filter(h => h.sessions >= 3).reduce((a, b) => b.edit_rate > a.edit_rate ? b : a, chartData[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">
          Peak activity at {peakHour.displayLabel} — but peak <span className="text-green">productivity</span> is at {mostProductiveHour.displayLabel}.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          Volume and quality don't align. The hour with the most sessions isn't the hour
          where code actually gets written. The green bars show sessions that produce edits.
        </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-5"
      >
        <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
          Sessions vs Edit Rate by Hour ({tz})
        </h3>
        <ResponsiveContainer width="100%" height={320}>
          <ComposedChart data={chartData} margin={{ bottom: 20 }}>
            <XAxis
              dataKey="displayHour"
              tick={{ fontSize: 10 }}
              label={{ value: `Hour (${tz})`, position: 'insideBottom', offset: -10, fontSize: 11, fill: '#63637a' }}
            />
            <YAxis
              yAxisId="left"
              tick={{ fontSize: 10 }}
              label={{ value: 'Sessions', angle: -90, position: 'insideLeft', fontSize: 11, fill: '#63637a' }}
            />
            <YAxis
              yAxisId="right"
              orientation="right"
              tick={{ fontSize: 10 }}
              tickFormatter={(v) => `${v}%`}
              label={{ value: 'Edit Rate %', angle: 90, position: 'insideRight', fontSize: 11, fill: '#34d399' }}
            />
            <Tooltip content={<CustomTooltip />} />
            <Bar yAxisId="left" dataKey="sessions" fill="#818cf8" radius={[3, 3, 0, 0]} opacity={0.7} />
            <Bar yAxisId="left" dataKey="sessions_with_edits" fill="#34d399" radius={[3, 3, 0, 0]} />
            <Line yAxisId="right" dataKey="edit_rate" stroke="#fbbf24" strokeWidth={2} dot={{ r: 3, fill: '#fbbf24' }} />
          </ComposedChart>
        </ResponsiveContainer>
        <div className="flex flex-wrap gap-4 justify-center mt-3 text-xs text-text-3">
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-sm bg-accent opacity-70" />
            Total sessions
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-sm bg-green" />
            Sessions with edits
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-full bg-amber" />
            Edit rate %
          </div>
        </div>
      </motion.div>
    </section>
  );
}
