import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { AudienceCount } from "@/lib/voters/types";
import {
  CheckCircle2,
  MessageCircle,
  Phone,
  Mail,
  Radio,
  Save,
  Sparkles,
  TrendingUp,
} from "lucide-react";

interface Props {
  stats: AudienceCount | undefined;
  onSave?: () => void;
  saving?: boolean;
}

const channelIcons = [
  { key: "SMS", icon: MessageCircle, reach: 0.94 },
  { key: "WhatsApp", icon: Radio, reach: 0.71 },
  { key: "Voice", icon: Phone, reach: 0.62 },
  { key: "Email", icon: Mail, reach: 0.38 },
];

function compactNumber(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return n.toString();
}

export function AudienceStats({ stats, onSave, saving }: Props) {
  const matched = stats?.total ?? 0;
  const optedIn = stats?.optedIn ?? 0;
  const optedInRate = matched ? optedIn / matched : 0;
  const stateBreakdown = stats?.byState.slice(0, 6) ?? [];
  const maxBreakdown = stateBreakdown[0]?.count ?? 1;

  return (
    <div className="space-y-4">
      <Card className="bg-gradient-to-br from-primary/5 via-accent/5 to-transparent border-primary/20">
        <CardHeader className="pb-2">
          <div className="flex items-center justify-between">
            <CardTitle className="text-sm flex items-center gap-2">
              <Sparkles className="h-4 w-4 text-primary" /> Estimated audience
            </CardTitle>
            <Badge variant="secondary" className="text-[10px] h-4">
              Live
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <div className="text-3xl font-semibold tracking-tight tabular-nums">
              {compactNumber(matched)}
            </div>
            <div className="mt-1 text-[11px] text-muted-foreground">
              {matched.toLocaleString()} matched · {optedIn.toLocaleString()} opted in
            </div>
          </div>

          <div className="space-y-1.5">
            <div className="flex justify-between text-[11px]">
              <span className="text-muted-foreground flex items-center gap-1">
                <CheckCircle2 className="h-3 w-3 text-success" /> Consent rate
              </span>
              <span className="font-medium tabular-nums">{(optedInRate * 100).toFixed(1)}%</span>
            </div>
            <Progress value={optedInRate * 100} className="h-1.5" />
          </div>

          <div className="grid grid-cols-2 gap-2">
            <Button size="sm" className="gap-1.5">
              <TrendingUp className="h-3.5 w-3.5" /> Use for campaign
            </Button>
            <Button
              size="sm"
              variant="outline"
              className="gap-1.5"
              onClick={onSave}
              disabled={!onSave || saving}
            >
              <Save className="h-3.5 w-3.5" /> {saving ? "Saving…" : "Save segment"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm">Channel reach forecast</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {channelIcons.map(({ key, icon: Icon, reach }) => {
            const value = Math.round(matched * reach);
            return (
              <div key={key}>
                <div className="flex items-center justify-between text-xs">
                  <span className="flex items-center gap-1.5">
                    <Icon className="h-3.5 w-3.5 text-primary" /> {key}
                  </span>
                  <span className="font-medium tabular-nums">{compactNumber(value)}</span>
                </div>
                <div className="mt-1 h-1.5 rounded-full bg-muted overflow-hidden">
                  <div
                    className="h-full bg-gradient-to-r from-primary to-accent"
                    style={{ width: `${reach * 100}%` }}
                  />
                </div>
              </div>
            );
          })}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm">Geographic breakdown</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          {stateBreakdown.length === 0 && (
            <div className="text-[11px] text-muted-foreground py-4 text-center">
              Adjust filters to see breakdown.
            </div>
          )}
          {stateBreakdown.map(({ state, count }) => (
            <div key={state}>
              <div className="flex items-center justify-between text-xs">
                <span>{state}</span>
                <span className="font-medium tabular-nums text-muted-foreground">
                  {count.toLocaleString()}
                </span>
              </div>
              <div className="mt-1 h-1.5 rounded-full bg-muted overflow-hidden">
                <div
                  className="h-full bg-chart-1"
                  style={{ width: `${(count / maxBreakdown) * 100}%` }}
                />
              </div>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
