"use client";

import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { copyTextToClipboard } from "@/lib/clipboard-write";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

function splitPhoneField(value?: string | null): string[] {
  if (!value?.trim()) return [];
  return value
    .split(",")
    .map((p) => p.trim())
    .filter(Boolean);
}

function splitEmailField(value?: string | null): string[] {
  if (!value?.trim()) return [];
  return value
    .split(",")
    .map((e) => e.trim())
    .filter(Boolean);
}

/** Primary email field, comma-split when multiple addresses are stored in one string. */
export function collectDealEmails(deal: {
  email?: string | null;
}): string[] {
  const seen = new Set<string>();
  const out: string[] = [];
  for (const part of splitEmailField(deal.email)) {
    const normalized = part.toLowerCase();
    if (!seen.has(normalized)) {
      seen.add(normalized);
      out.push(part);
    }
  }
  return out;
}

/** Primary + home phone, deduped, comma-split per field (matches lead detail view). */
export function collectDealPhoneNumbers(deal: {
  phone?: string | null;
  homePhone?: string | null;
}): string[] {
  const seen = new Set<string>();
  const out: string[] = [];
  for (const part of [
    ...splitPhoneField(deal.phone),
    ...splitPhoneField(deal.homePhone),
  ]) {
    if (!seen.has(part)) {
      seen.add(part);
      out.push(part);
    }
  }
  return out;
}

type CopyablePhoneBadgesProps = {
  phones: string[];
  className?: string;
  emptyClassName?: string;
  /** Stop row click when copying inside tables. */
  stopPropagation?: boolean;
};

export function CopyablePhoneBadges({
  phones,
  className,
  emptyClassName = "text-[12px] text-gray-300",
  stopPropagation = true,
}: CopyablePhoneBadgesProps) {
  if (phones.length === 0) {
    return <span className={emptyClassName}>—</span>;
  }

  const handleCopy = (phone: string) => (e: React.MouseEvent) => {
    if (stopPropagation) e.stopPropagation();
    void copyTextToClipboard(phone).then((ok) =>
      ok ? toast.success("Phone copied") : toast.error("Could not copy phone"),
    );
  };

  return (
    <div className={cn("flex flex-wrap gap-1", className)}>
      {phones.map((phone, i) => (
        <Badge
          key={`${phone}-${i}`}
          variant="secondary"
          role="button"
          tabIndex={0}
          className="cursor-copy bg-[#6C63FF]/5 text-[#6C63FF] border-[#6C63FF]/20 hover:bg-[#6C63FF]/10 transition-colors h-auto py-0.5 px-2 text-[11px] font-semibold rounded-md font-['Lexend_Deca'] select-all"
          title={`Copy ${phone}`}
          onClick={handleCopy(phone)}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              handleCopy(phone)(e as unknown as React.MouseEvent);
            }
          }}
        >
          {phone}
        </Badge>
      ))}
    </div>
  );
}

type CopyableEmailBadgesProps = {
  emails: string[];
  className?: string;
  emptyClassName?: string;
  stopPropagation?: boolean;
  /** Slightly smaller badges for name column under customer title. */
  compact?: boolean;
};

export function CopyableEmailBadges({
  emails,
  className,
  emptyClassName = "text-[12px] text-gray-300",
  stopPropagation = true,
  compact = false,
}: CopyableEmailBadgesProps) {
  if (emails.length === 0) {
    return <span className={emptyClassName}>—</span>;
  }

  const handleCopy = (email: string) => (e: React.MouseEvent) => {
    if (stopPropagation) e.stopPropagation();
    void copyTextToClipboard(email).then((ok) =>
      ok ? toast.success("Email copied") : toast.error("Could not copy email"),
    );
  };

  return (
    <div className={cn("flex flex-wrap gap-1", className)}>
      {emails.map((email, i) => (
        <Badge
          key={`${email}-${i}`}
          variant="secondary"
          role="button"
          tabIndex={0}
          className={cn(
            "cursor-copy bg-[#6C63FF]/5 text-[#6C63FF] border-[#6C63FF]/20 hover:bg-[#6C63FF]/10 transition-colors h-auto font-semibold rounded-md font-['Lexend_Deca'] select-all max-w-full",
            compact
              ? "py-0.5 px-2 text-[11px] truncate"
              : "py-0.5 px-2 text-[11px]",
          )}
          title={`Copy ${email}`}
          onClick={handleCopy(email)}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              handleCopy(email)(e as unknown as React.MouseEvent);
            }
          }}
        >
          {email}
        </Badge>
      ))}
    </div>
  );
}
