import { Activity } from "lucide-react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { LocalizedText, SectorRecordReport } from "./types";

interface MonthlyActivitySectionProps {
  reports: SectorRecordReport[];
  getName: (name: LocalizedText) => string;
}

export function MonthlyActivitySection({
  reports,
  getName,
}: MonthlyActivitySectionProps) {
  const chartData = reports
    .map((report) => ({
      name: report.groupName
        ? getName(report.groupName)
        : getName(report.sectorName),
      sector: getName(report.sectorName),
      incoming: report.incoming.thisMonth,
      outgoing: report.outgoing.thisMonth,
    }))
    .sort(
      (a, b) =>
        b.incoming + b.outgoing - (a.incoming + a.outgoing),
    );

  const monthlyIncoming = chartData.reduce(
    (total, item) => total + item.incoming,
    0,
  );
  const monthlyOutgoing = chartData.reduce(
    (total, item) => total + item.outgoing,
    0,
  );
  const monthlyTotal = monthlyIncoming + monthlyOutgoing;
  const distribution = chartData.slice(0, 5).map((item) => ({
    ...item,
    share: monthlyTotal
      ? Math.round(((item.incoming + item.outgoing) / monthlyTotal) * 100)
      : 0,
  }));
  const chartWidth = Math.max(700, chartData.length * 140);

  return (
    <section className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="flex items-center gap-3 border-b px-5 py-4">
        <span className="rounded-lg bg-primary/10 p-2 text-primary">
          <Activity className="size-5" />
        </span>
        <div>
          <h2 className="font-semibold">Monthly activity</h2>
          <p className="text-xs text-muted-foreground">
            Incoming and outgoing records by sector or group this month
          </p>
        </div>
      </div>

      <div className="grid xl:grid-cols-[minmax(0,3fr)_minmax(230px,1fr)]">
        <div className="border-b p-5 xl:border-b-0 xl:border-r">
          <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
            <div>
              <h3 className="text-sm font-semibold">Activity comparison</h3>
              <p className="text-xs text-muted-foreground">
                Incoming vs outgoing records
              </p>
            </div>
            <p className="text-xs text-muted-foreground">
              Total: {monthlyTotal.toLocaleString()}
            </p>
        </div>
        <div className="min-h-80 overflow-x-auto">
          <div className="h-80" style={{ width: chartWidth }}>
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
              data={chartData}
              margin={{ top: 8, right: 8, left: 0, bottom: 48 }}>
              <CartesianGrid strokeDasharray="3 3" vertical={false} />
              <XAxis
                dataKey="name"
                angle={-30}
                textAnchor="end"
                interval={0}
                height={72}
                tick={{ fontSize: 11 }}
              />
              <YAxis allowDecimals={false} />
              <Tooltip
                formatter={(value, name) => [
                  Number(value ?? 0).toLocaleString(),
                  String(name).toLowerCase() === "incoming"
                    ? "Incoming"
                    : "Outgoing",
                ]}
                labelFormatter={(label, payload) => {
                  const sector = payload?.[0]?.payload?.sector;
                  return sector && sector !== label
                    ? `${sector} — ${label}`
                    : label;
                }}
              />
              <Legend verticalAlign="top" height={32} />
              <Bar
                dataKey="incoming"
                name="Incoming"
                fill="#10b981"
                radius={[4, 4, 0, 0]}
              />
              <Bar
                dataKey="outgoing"
                name="Outgoing"
                fill="#8b5cf6"
                radius={[4, 4, 0, 0]}
              />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
        </div>

        <aside className="p-5">
          <h3 className="text-sm font-semibold">Sector distribution</h3>
          <p className="mb-5 text-xs text-muted-foreground">
            Share of monthly activity
          </p>
          <div className="space-y-5">
            {distribution.map((item, index) => (
              <div key={`${item.sector}-${item.name}`}>
                <div className="mb-2 flex items-center gap-3">
                  <span
                    className="flex size-9 shrink-0 items-center justify-center rounded-md text-xs font-bold text-white"
                    style={{
                      backgroundColor: `hsl(158 64% ${26 + index * 8}%)`,
                    }}>
                    {item.share}%
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-xs font-semibold uppercase">
                      {item.name}
                    </p>
                    <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-muted">
                      <div
                        className="h-full rounded-full bg-emerald-700"
                        style={{ width: `${item.share}%` }}
                      />
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </aside>
      </div>
    </section>
  );
}
