'use client';

import {
  ResponsiveContainer,
  LineChart, Line,
  BarChart, Bar,
  PieChart, Pie, Cell,
  XAxis, YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from 'recharts';

export const COLORS = {
  saffron: 'hsl(30 80% 50%)',
  moss:    'hsl(140 25% 30%)',
  ink:     'hsl(30 18% 16%)',
  rust:    'hsl(10 60% 45%)',
  series:  [
    'hsl(30 80% 50%)',
    'hsl(140 25% 30%)',
    'hsl(30 18% 16%)',
    'hsl(10 60% 45%)',
    'hsl(200 40% 45%)',
    'hsl(260 30% 50%)',
  ],
};

const tickStyle = { fontSize: 11, fontFamily: 'inherit', fill: 'hsl(30 18% 50%)' };
const tooltipStyle = {
  borderRadius: '8px',
  border: '1px solid hsl(30 20% 88%)',
  backgroundColor: 'hsl(30 20% 97%)',
  fontSize: '12px',
  color: 'hsl(30 18% 16%)',
};

function Empty() {
  return <p className="py-8 text-center text-sm text-ink-300">No data for this period.</p>;
}

// ---- Daily trend line chart -----------------------------------------------

export function DailyTrendChart({ data }: { data: Array<{ date: string; count: number }> }) {
  if (!data.length) return <Empty />;
  return (
    <ResponsiveContainer width="100%" height={220}>
      <LineChart data={data} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(30 20% 90%)" />
        <XAxis dataKey="date" tick={tickStyle} tickFormatter={(d: string) => d.slice(5)} interval="preserveStartEnd" />
        <YAxis tick={tickStyle} allowDecimals={false} />
        <Tooltip contentStyle={tooltipStyle} labelFormatter={(d) => `Date: ${d}`} />
        <Line
          type="monotone"
          dataKey="count"
          name="Vihars"
          stroke={COLORS.saffron}
          strokeWidth={2}
          dot={false}
          activeDot={{ r: 4 }}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}

// ---- Vihars by locality bar chart -----------------------------------------

export function ByLocalityChart({ data }: { data: Array<{ name: string; count: number }> }) {
  if (!data.length) return <Empty />;
  const sorted = [...data].sort((a, b) => b.count - a.count).slice(0, 10);
  return (
    <ResponsiveContainer width="100%" height={260}>
      <BarChart data={sorted} layout="vertical" margin={{ top: 4, right: 16, left: 4, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(30 20% 90%)" horizontal={false} />
        <XAxis type="number" tick={tickStyle} allowDecimals={false} />
        <YAxis type="category" dataKey="name" tick={{ ...tickStyle, fontSize: 10 }} width={80} />
        <Tooltip contentStyle={tooltipStyle} />
        <Bar dataKey="count" name="Vihars" fill={COLORS.saffron} radius={[0, 4, 4, 0]} />
      </BarChart>
    </ResponsiveContainer>
  );
}

// ---- Vihars by samuday pie chart ------------------------------------------

export function BySamudayChart({ data }: { data: Array<{ name: string; count: number }> }) {
  if (!data.length) return <Empty />;
  return (
    <ResponsiveContainer width="100%" height={220}>
      <PieChart>
        <Pie
          data={data}
          dataKey="count"
          nameKey="name"
          cx="50%"
          cy="50%"
          outerRadius={80}
          label={({ name, percent }: { name: string; percent: number }) =>
            `${name} ${(percent * 100).toFixed(0)}%`
          }
          labelLine={false}
        >
          {data.map((entry, i) => (
            <Cell key={entry.name} fill={COLORS.series[i % COLORS.series.length]} />
          ))}
        </Pie>
        <Tooltip contentStyle={tooltipStyle} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: '11px' }} />
      </PieChart>
    </ResponsiveContainer>
  );
}

// ---- Top contributors horizontal bar chart --------------------------------

export function TopContributorsChart({
  data,
}: {
  data: Array<{ fullName: string; totalKm: number; viharCount: number }>;
}) {
  if (!data.length) return <Empty />;
  return (
    <ResponsiveContainer width="100%" height={Math.max(200, data.length * 28 + 40)}>
      <BarChart data={data} layout="vertical" margin={{ top: 4, right: 40, left: 4, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(30 20% 90%)" horizontal={false} />
        <XAxis type="number" tick={tickStyle} unit=" km" />
        <YAxis type="category" dataKey="fullName" tick={{ ...tickStyle, fontSize: 10 }} width={80} />
        <Tooltip
          contentStyle={tooltipStyle}
          formatter={(val: number, name: string) =>
            name === 'totalKm' ? [`${val.toFixed(1)} km`, 'Distance'] : [val, 'Vihars']
          }
        />
        <Bar dataKey="totalKm" name="totalKm" fill={COLORS.moss} radius={[0, 4, 4, 0]}>
          {data.map((entry, i) => (
            <Cell key={entry.fullName} fill={COLORS.series[i % COLORS.series.length]} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}
