"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { ArrowLeft, Rocket, Trash2, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { formatDateTime, initials } from "@/lib/utils";

type Any = any;

export function BroadcastDetail({
  broadcast,
  recipientCount,
}: {
  broadcast: Any;
  recipientCount: number;
}) {
  const router = useRouter();
  const [launching, setLaunching] = useState(false);
  const [resuming, setResuming] = useState(false);
  const [stopping, setStopping] = useState(false);
  const audience = broadcast.audience ?? {};
  const done = ["DONE", "SENDING", "FAILED"].includes(broadcast.status);

  useEffect(() => {
    if (broadcast.status === "SENDING") {
      const interval = setInterval(() => {
        router.refresh();
      }, 3000);
      return () => clearInterval(interval);
    }
  }, [broadcast.status, router]);

  async function launch() {
    if (!confirm("Launch this broadcast now? Messages are sent through your connected WhatsApp number.")) return;
    setLaunching(true);
    const res = await fetch(`/api/broadcasts/${broadcast.id}`, { method: "POST" });
    const json = await res.json().catch(() => ({}));
    setLaunching(false);
    if (!res.ok) return toast.error(json.error ?? "Launch failed.");
    toast.success(`Launched. Sent ${json.sent}, failed ${json.failed}.`);
    router.refresh();
  }

  async function remove() {
    if (!confirm("Are you sure you want to delete this broadcast?")) return;
    try {
      const res = await fetch(`/api/broadcasts/${broadcast.id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Failed");
      toast.success("Broadcast deleted");
      router.push("/broadcasts");
    } catch {
      toast.error("Failed to delete broadcast");
    }
  }

  async function handleResume() {
    if (!confirm("Are you sure you want to force-resume this broadcast? Use this only if the broadcast has frozen or failed midway.")) return;
    setResuming(true);
    try {
      const res = await fetch(`/api/broadcasts/${broadcast.id}/resume`, { method: "POST" });
      if (!res.ok) throw new Error("Failed");
      toast.success("Broadcast resumed in background");
      router.refresh();
    } catch {
      toast.error("Failed to resume");
    } finally {
      setResuming(false);
    }
  }

  async function handleStop() {
    if (!confirm("Are you sure you want to stop this broadcast? Remaining messages will not be sent.")) return;
    setStopping(true);
    try {
      const res = await fetch(`/api/broadcasts/${broadcast.id}/stop`, { method: "POST" });
      if (!res.ok) throw new Error("Failed");
      toast.success("Broadcast stopped");
      router.refresh();
    } catch {
      toast.error("Failed to stop broadcast");
    } finally {
      setStopping(false);
    }
  }

  const getPercent = (val: number) => broadcast.totalCount > 0 ? Math.round((val / broadcast.totalCount) * 100) : 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <button onClick={() => router.push("/broadcasts")} className="rounded-lg p-2 text-muted-foreground hover:bg-muted hover:text-foreground">
          <ArrowLeft className="h-5 w-5" />
        </button>
        <div className="min-w-0">
          <h1 className="truncate text-xl font-bold text-foreground">{broadcast.name}</h1>
          <p className="text-sm text-muted-foreground">Created {formatDateTime(broadcast.createdAt)}</p>
        </div>
        <div className="ml-auto flex gap-2">
          {!done && (
            <Button onClick={launch} loading={launching}>
              <Rocket className="h-4 w-4" /> Launch
            </Button>
          )}
          <Button variant="ghost" onClick={remove} className="text-red-600 hover:bg-red-50">
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
        <Card className="border-indigo-100 bg-indigo-50/50 dark:border-indigo-900 dark:bg-indigo-950/20">
          <CardBody className="flex flex-col items-center justify-center py-4 h-full gap-2">
            <Button 
              onClick={handleResume} 
              disabled={resuming || stopping || (broadcast.status !== "SENDING" && broadcast.status !== "FAILED")}
              className="w-full font-semibold"
            >
              {resuming ? "Resuming..." : "Resume"}
            </Button>
            <Button 
              onClick={handleStop} 
              disabled={stopping || resuming || broadcast.status !== "SENDING"}
              variant="destructive"
              className="w-full font-semibold"
            >
              {stopping ? "Stopping..." : "Stop"}
            </Button>
          </CardBody>
        </Card>
        <Card className="border-blue-100 bg-blue-50/50 dark:border-blue-900 dark:bg-blue-950/20">
          <CardBody>
            <p className="text-xs font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-400">Pcs Sent</p>
            <p className="mt-1 flex items-baseline gap-1.5 text-2xl font-bold text-blue-900 dark:text-blue-100">
              {broadcast.sentCount}
              <span className="text-[13px] font-semibold opacity-60">({getPercent(broadcast.sentCount)}%)</span>
            </p>
          </CardBody>
        </Card>
        <Card className="border-amber-100 bg-amber-50/50 dark:border-amber-900 dark:bg-amber-950/20">
          <CardBody>
            <p className="text-xs font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">Pcs Due</p>
            <p className="mt-1 flex items-baseline gap-1.5 text-2xl font-bold text-amber-900 dark:text-amber-100">
              {Math.max(0, broadcast.totalCount - broadcast.sentCount - broadcast.failedCount)}
              <span className="text-[13px] font-semibold opacity-60">({getPercent(Math.max(0, broadcast.totalCount - broadcast.sentCount - broadcast.failedCount))}%)</span>
            </p>
          </CardBody>
        </Card>
        <Card className="border-red-100 bg-red-50/50 dark:border-red-900 dark:bg-red-950/20">
          <CardBody>
            <p className="text-xs font-semibold uppercase tracking-wide text-red-600 dark:text-red-400">Contact Invalid</p>
            <p className="mt-1 flex items-baseline gap-1.5 text-2xl font-bold text-red-900 dark:text-red-100">
              {broadcast.failedCount}
              <span className="text-[13px] font-semibold opacity-60">({getPercent(broadcast.failedCount)}%)</span>
            </p>
          </CardBody>
        </Card>
        <Card className="border-emerald-100 bg-emerald-50/50 dark:border-emerald-900 dark:bg-emerald-950/20">
          <CardBody className="flex flex-col justify-center py-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-emerald-600 dark:text-emerald-400">Time</p>
            <div className="mt-1.5 flex flex-col gap-1 text-[13px] font-medium text-emerald-900 dark:text-emerald-100">
              <div className="flex items-center justify-between">
                <span className="opacity-70">Start:</span>
                <span>{broadcast.startedAt ? formatDateTime(broadcast.startedAt).split(',').pop()?.trim() : "—"}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="opacity-70">End:</span>
                <span>{broadcast.finishedAt ? formatDateTime(broadcast.finishedAt).split(',').pop()?.trim() : "—"}</span>
              </div>
            </div>
          </CardBody>
        </Card>
      </div>

      <div className="flex flex-col lg:flex-row gap-4">
        {/* Status Card */}
        <Card className="flex-shrink-0 min-w-[120px]">
          <CardBody className="flex flex-col justify-center h-full">
            <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Status</p>
            <p className="mt-1 text-xl font-bold text-foreground">
              {broadcast.status}
            </p>
          </CardBody>
        </Card>

        {/* Funnel */}
        <Card className="flex-1 overflow-hidden border-indigo-100 dark:border-indigo-900/50">
          <CardBody className="p-0 flex flex-col sm:flex-row h-full">
            {[
              ["Recipients", broadcast.totalCount, "bg-indigo-50/80 dark:bg-indigo-950/30", "text-indigo-600 dark:text-indigo-400", "border-indigo-100 dark:border-indigo-900/50"],
              ["Sent", broadcast.sentCount, "bg-blue-50/80 dark:bg-blue-950/30", "text-blue-600 dark:text-blue-400", "border-blue-100 dark:border-blue-900/50"],
              ["Delivered", broadcast.deliveredCount, "bg-cyan-50/80 dark:bg-cyan-950/30", "text-cyan-600 dark:text-cyan-400", "border-cyan-100 dark:border-cyan-900/50"],
              ["Read", broadcast.readCount, "bg-teal-50/80 dark:bg-teal-950/30", "text-teal-600 dark:text-teal-400", "border-teal-100 dark:border-teal-900/50"],
            ].map(([label, value, bgClass, textClass, borderClass], idx, arr) => (
              <div key={label as string} className={`relative flex-1 p-4 sm:p-5 flex flex-col justify-center ${idx !== 0 ? 'border-t sm:border-t-0 sm:border-l' : ''} ${borderClass}`}>
                <div className={`absolute inset-0 z-0 ${bgClass}`} />
                <div className="relative z-10">
                  <div className="flex items-center justify-between gap-2">
                     <p className={`text-[11px] font-bold uppercase tracking-wider ${textClass}`}>{label}</p>
                     {/* Funnel icon connector if not last item */}
                     {idx !== arr.length - 1 && (
                       <div className="hidden sm:block absolute -right-3 top-1/2 -translate-y-1/2 z-20 text-muted-foreground/30">
                         <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
                       </div>
                     )}
                  </div>
                  <p className="mt-2 flex items-baseline gap-1.5 text-2xl font-bold text-foreground">
                    {String(value)}
                    {label !== "Recipients" && (
                      <span className="text-[12px] font-semibold text-muted-foreground">({getPercent(Number(value))}%)</span>
                    )}
                  </p>
                </div>
              </div>
            ))}
          </CardBody>
        </Card>

        {/* Failed Card */}
        <Card className="flex-shrink-0 min-w-[120px] border-red-100 bg-red-50/50 dark:border-red-900 dark:bg-red-950/20">
          <CardBody className="flex flex-col justify-center h-full">
            <p className="text-xs font-semibold uppercase tracking-wide text-red-600 dark:text-red-400">Failed</p>
            <p className="mt-1 flex items-baseline gap-1.5 text-xl font-bold text-red-900 dark:text-red-100">
              {broadcast.failedCount}
              <span className="text-[11px] font-semibold opacity-60">({getPercent(broadcast.failedCount)}%)</span>
            </p>
          </CardBody>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Audience</CardTitle>
        </CardHeader>
        <CardBody className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
          <span className="rounded-lg bg-muted px-3 py-1 text-xs font-medium">All contacts</span>
          {(audience.tagIds ?? []).length > 0 && <span className="rounded-lg bg-indigo-100 px-3 py-1 text-xs font-medium text-indigo-700">with tags</span>}
          <span className="text-muted-foreground">{recipientCount} match now</span>
        </CardBody>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Recipients ({broadcast.recipients.length} of {recipientCount})</CardTitle>
        </CardHeader>
        <CardBody className="px-0">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted-foreground">
                <th className="px-5 py-2 font-medium">Contact</th>
                <th className="px-5 py-2 font-medium">Status</th>
                <th className="px-5 py-2 font-medium">Error</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {broadcast.recipients.map((r: Any) => (
                <tr key={r.id}>
                  <td className="flex items-center gap-2 px-5 py-2.5">
                    <span className="flex h-6 w-6 items-center justify-center rounded-full bg-indigo-100 text-[10px] font-semibold text-indigo-700">
                      {initials(r.contact.name)}
                    </span>
                    <span className="text-foreground">{r.contact.name}</span>
                    <span className="text-xs text-muted-foreground">{r.contact.phone}</span>
                  </td>
                  <td className="px-5 py-2.5">
                    <Badge
                      tone={
                        r.status === "READ" ? "violet" : r.status === "DELIVERED" ? "green" : r.status === "SENT" ? "blue" : r.status === "FAILED" ? "red" : "gray"
                      }
                    >
                      {r.status.toLowerCase()}
                    </Badge>
                  </td>
                  <td className="max-w-52 truncate px-5 py-2.5 text-xs text-red-600">{r.error ?? "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </CardBody>
      </Card>
    </div>
  );
}
