import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
  Tooltip,
} from 'recharts';

interface AudienceChartProps {
  female: number;
  male: number;
  ageDistribution?: Record<string, number>;
  topCountries?: { name: string; percentage: number }[];
  topCities?: { name: string; percentage: number }[];
}

const COLORS = ['#3b82f6', '#94a3b8'];

const AGE_COLORS = [
  '#6366f1',
  '#8b5cf6',
  '#a855f7',
  '#d946ef',
  '#ec4899',
  '#f43f5e',
  '#94a3b8',
];

function DemographicBars({
  title,
  rows,
}: {
  title: string;
  rows: { label: string; pct: number }[];
}) {
  if (!rows.length) return null;
  return (
    <div className="mt-4 text-left">
      <p className="text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2">{title}</p>
      <ul className="space-y-2">
        {rows.map((r) => (
          <li key={r.label}>
            <div className="flex justify-between text-xs text-zinc-400 mb-0.5">
              <span className="truncate pr-2">{r.label}</span>
              <span className="tabular-nums shrink-0">{r.pct.toFixed(1)}%</span>
            </div>
            <div className="h-1.5 rounded-full bg-gray-100 overflow-hidden">
              <div
                className="h-full rounded-full bg-brand-500"
                style={{ width: `${Math.min(100, r.pct)}%` }}
              />
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

export function AudienceChart({
  female,
  male,
  ageDistribution,
  topCountries,
  topCities,
}: AudienceChartProps) {
  const other = Math.max(0, 100 - female - male);
  const data = [
    { name: 'Female', value: female },
    { name: 'Male', value: male },
    ...(other > 0 ? [{ name: 'Other', value: other }] : []),
  ];

  const colors = other > 0 ? [...COLORS, '#cbd5e1'] : COLORS;

  const ageRows =
    ageDistribution && Object.keys(ageDistribution).length > 0
      ? Object.entries(ageDistribution)
          .map(([label, pct]) => ({ label, pct: Number(pct) }))
          .sort((a, b) => b.pct - a.pct)
      : [];

  const countryRows =
    topCountries?.map((c) => ({ label: c.name, pct: Number(c.percentage) })) ?? [];

  const cityRows = topCities?.map((c) => ({ label: c.name, pct: Number(c.percentage) })) ?? [];

  return (
    <div>
      <ResponsiveContainer width="100%" height={250}>
        <PieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            innerRadius={60}
            outerRadius={90}
            paddingAngle={3}
            dataKey="value"
          >
            {data.map((_, index) => (
              <Cell key={index} fill={colors[index % colors.length]} />
            ))}
          </Pie>
          <Tooltip
            contentStyle={{
              backgroundColor: '#ffffff',
              border: '1px solid #e5e7eb',
              borderRadius: '8px',
              color: '#111827',
              boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
            }}
            formatter={(value) => `${Number(value).toFixed(1)}%`}
          />
          <Legend
            formatter={(value: string) => (
              <span style={{ color: '#6b7280', fontSize: 13 }}>{value}</span>
            )}
          />
        </PieChart>
      </ResponsiveContainer>

      {ageRows.length > 0 && (
        <div className="mt-2">
          <p className="text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2 text-center">
            Age distribution
          </p>
          <ResponsiveContainer width="100%" height={Math.min(220, 40 + ageRows.length * 36)}>
            <PieChart>
              <Pie
                data={ageRows.map((r) => ({ name: r.label, value: r.pct }))}
                cx="50%"
                cy="50%"
                outerRadius={70}
                dataKey="value"
                label={({ name, percent }) =>
                  `${name} ${((percent ?? 0) * 100).toFixed(0)}%`
                }
              >
                {ageRows.map((_, index) => (
                  <Cell key={index} fill={AGE_COLORS[index % AGE_COLORS.length]} />
                ))}
              </Pie>
              <Tooltip formatter={(value) => `${Number(value).toFixed(1)}%`} />
            </PieChart>
          </ResponsiveContainer>
        </div>
      )}

      <DemographicBars title="Top countries" rows={countryRows} />
      <DemographicBars title="Top cities" rows={cityRows} />
    </div>
  );
}
