import {
  CalendarClock,
  CheckCircle2,
  ExternalLink,
  FolderOpen,
  MapPin,
  Tag,
  User,
  XCircle,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { BriefInboxItem } from "@/lib/briefInbox";

interface BriefReviewCardProps {
  item: BriefInboxItem;
  mode: "new" | "rejected";
  busy?: boolean;
  onApprove?: () => void;
  onReject?: () => void;
}

function safeUrl(value: string) {
  const clean = value.trim();
  if (!/^https?:\/\//i.test(clean)) return "";
  return clean;
}

function openUrl(value: string) {
  const url = safeUrl(value);
  if (!url) return;
  window.open(url, "_blank", "noopener,noreferrer");
}

function formatDate(value: number | null) {
  if (!value || !Number.isFinite(value)) return "—";
  return new Intl.DateTimeFormat("es-DO", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  }).format(new Date(value));
}

export function BriefReviewCard({
  item,
  mode,
  busy = false,
  onApprove,
  onReject,
}: BriefReviewCardProps) {
  const isRejected = mode === "rejected";
  const mainBriefUrl = safeUrl(item.documentLink) || safeUrl(item.briefLink);
  const folderUrl = safeUrl(item.briefLink);

  return (
    <article
      className={cn(
        "overflow-hidden rounded-2xl border bg-card shadow-sm transition-shadow hover:shadow-md",
        isRejected ? "border-red-200/70" : "border-amber-200/80",
      )}
    >
      <div
        className={cn(
          "flex min-h-14 items-start justify-between gap-3 px-4 py-3",
          isRejected ? "bg-red-50" : "bg-amber-50",
        )}
      >
        <div className="min-w-0">
          <div className="mb-1.5 flex flex-wrap items-center gap-1.5">
            <Badge
              variant="secondary"
              className={cn(
                "h-5 px-2 text-[10px] font-semibold",
                isRejected
                  ? "bg-red-100 text-red-800 hover:bg-red-100"
                  : "bg-amber-100 text-amber-900 hover:bg-amber-100",
              )}
            >
              {isRejected ? "Rechazado" : "Nuevo · CDC Brief"}
            </Badge>
          </div>
          <h3 className="line-clamp-2 text-sm font-semibold leading-snug text-foreground">
            {item.title || "Brief sin título"}
          </h3>
        </div>
      </div>

      <div className="space-y-3 p-4">
        <div className="space-y-2.5">
          <InfoRow icon={<Tag className="h-3.5 w-3.5" />} label="Cliente" value={item.client} />
          <InfoRow icon={<Tag className="h-3.5 w-3.5" />} label="Marca" value={item.brand} />
          <InfoRow icon={<MapPin className="h-3.5 w-3.5" />} label="País" value={item.country} />
          <InfoRow
            icon={<User className="h-3.5 w-3.5" />}
            label="Solicita"
            value={item.requestedBy}
          />
          <InfoRow
            icon={<CalendarClock className="h-3.5 w-3.5" />}
            label="Creado"
            value={formatDate(item.sourceCreatedAt)}
          />
        </div>

        {(item.requestType || item.deliverableType || item.deliveryDate) && (
          <div className="rounded-xl border border-border/70 bg-muted/20 px-3 py-2.5 text-xs">
            {item.requestType && (
              <p>
                <span className="text-muted-foreground">Requerimiento:</span>{" "}
                <span className="font-medium text-foreground">{item.requestType}</span>
              </p>
            )}
            {item.deliverableType && (
              <p className={item.requestType ? "mt-1" : ""}>
                <span className="text-muted-foreground">Entregable:</span>{" "}
                <span className="font-medium text-foreground">{item.deliverableType}</span>
              </p>
            )}
            {item.deliveryDate && (
              <p className={item.requestType || item.deliverableType ? "mt-1" : ""}>
                <span className="text-muted-foreground">Entrega:</span>{" "}
                <span className="font-medium text-foreground">{item.deliveryDate}</span>
              </p>
            )}
          </div>
        )}

        {item.summary && (
          <p className="line-clamp-4 text-xs leading-relaxed text-muted-foreground">{item.summary}</p>
        )}

        {isRejected && (item.reviewedByName || item.reviewedAt) && (
          <div className="rounded-xl border border-red-100 bg-red-50/60 px-3 py-2 text-[11px] text-red-800">
            Revisado{item.reviewedByName ? ` por ${item.reviewedByName}` : ""}
            {item.reviewedAt ? ` · ${formatDate(item.reviewedAt)}` : ""}
            {item.rejectionReason ? ` · ${item.rejectionReason}` : ""}
          </div>
        )}

        <div className="flex flex-wrap gap-2 border-t border-border/70 pt-3">
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="h-8 gap-1.5 rounded-full px-3 text-xs"
            disabled={!mainBriefUrl || busy}
            onClick={() => openUrl(mainBriefUrl)}
          >
            <ExternalLink className="h-3.5 w-3.5" />
            Ver brief
          </Button>

          {folderUrl && folderUrl !== mainBriefUrl && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="h-8 gap-1.5 rounded-full px-3 text-xs"
              disabled={busy}
              onClick={() => openUrl(folderUrl)}
            >
              <FolderOpen className="h-3.5 w-3.5" />
              Carpeta
            </Button>
          )}

          <div className="ml-auto flex gap-2">
            {!isRejected && (
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8 gap-1.5 rounded-full border-red-200 px-3 text-xs text-red-700 hover:bg-red-50 hover:text-red-800"
                disabled={busy || !onReject}
                onClick={onReject}
              >
                <XCircle className="h-3.5 w-3.5" />
                No aprobar
              </Button>
            )}
            <Button
              type="button"
              size="sm"
              className="h-8 gap-1.5 rounded-full px-3 text-xs"
              disabled={busy || !onApprove}
              onClick={onApprove}
            >
              <CheckCircle2 className="h-3.5 w-3.5" />
              {busy ? "Procesando…" : "Aprobar"}
            </Button>
          </div>
        </div>
      </div>
    </article>
  );
}

function InfoRow({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div className="flex items-start gap-2 text-xs">
      <span className="mt-0.5 flex-shrink-0 text-muted-foreground">{icon}</span>
      <span className="w-14 flex-shrink-0 text-muted-foreground">{label}</span>
      <span className="truncate font-medium text-foreground">{value || "—"}</span>
    </div>
  );
}
