import { MapPin, User, Tag, Link2, FileCheck2, CheckCircle2, Clock3 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { colorHex } from "@/lib/colors";
import type { Project } from "@/lib/store";

interface ProjectCardProps {
  project: Project;
  onClick: () => void;
  onTimeClick?: () => void;
  showInternalAmount?: boolean;
}

export function ProjectCard({
  project,
  onClick,
  onTimeClick,
  showInternalAmount = false,
}: ProjectCardProps) {
  const closed = !!project.status;
  const internalAmount = Number(project.monto);
  const hasInternalAmount =
    showInternalAmount &&
    project.monto !== null &&
    Number.isFinite(internalAmount) &&
    internalAmount > 0;
  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      onClick();
    }
  };

  return (
    <div
      data-cdc-project-id={project.id}
      data-cdc-project-country={project.bu}
      data-cdc-project-name={project.nombre || "Sin título"}
      role="button"
      tabIndex={0}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      className={cn(
        "group block text-left w-full rounded-2xl bg-card overflow-hidden p-0 ring-1 ring-border cursor-pointer",
        "transition-all duration-200 hover:-translate-y-0.5",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
        closed && "opacity-65 hover:opacity-90",
      )}
      style={{
        boxShadow: closed ? "0 1px 2px oklch(0.5 0.02 280 / 0.04)" : "var(--shadow-soft)",
      }}
      onMouseEnter={(e) => {
        if (!closed) e.currentTarget.style.boxShadow = "var(--shadow-hover)";
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.boxShadow = closed
          ? "0 1px 2px oklch(0.5 0.02 280 / 0.04)"
          : "var(--shadow-soft)";
      }}
    >
      {/* Pestaña de color con título */}
      <div
        className="min-h-14 rounded-t-2xl px-4 py-3"
        style={{
          backgroundColor: closed ? "#9AA0A6" : colorHex(project.color),
        }}
      >
        <h3 className="text-white font-semibold text-sm leading-snug line-clamp-2 drop-shadow-sm">
          {project.nombre || "Sin título"}
        </h3>
      </div>

      {/* Cuerpo blanco */}
      <div className="p-4 space-y-2.5">
        <Row icon={<Tag className="w-3.5 h-3.5" />} label="Cliente" value={project.cliente} />
        <Row icon={<Tag className="w-3.5 h-3.5" />} label="Marca" value={project.marca} />
        <Row icon={<MapPin className="w-3.5 h-3.5" />} label="País" value={project.bu} />
        <Row icon={<User className="w-3.5 h-3.5" />} label="Solicita" value={project.solicitante} />

        <div className="flex items-center justify-between pt-2 mt-2 border-t border-border/70">
          <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
            {onTimeClick && (
              <button
                type="button"
                onClick={(event) => {
                  event.stopPropagation();
                  onTimeClick();
                }}
                onKeyDown={(event) => event.stopPropagation()}
                className="inline-flex h-7 items-center gap-1 rounded-full border border-border bg-card px-2.5 font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                title="Agregar o ver tiempo dedicado"
              >
                <Clock3 className="h-3.5 w-3.5" />
                Tiempo
              </button>
            )}
            {project.propuestaLinks.length > 0 && (
              <span className="flex items-center gap-1" title="Propuestas">
                <Link2 className="w-3 h-3" /> {project.propuestaLinks.length}
              </span>
            )}
            {project.afLinks.length > 0 && (
              <span className="flex items-center gap-1" title="Artes finales">
                <FileCheck2 className="w-3 h-3" /> AF·{project.afLinks.length}
              </span>
            )}
          </div>

          <div className="flex items-center gap-2">
            {hasInternalAmount && (
              <span
                className="text-sm font-semibold tabular-nums text-foreground"
                title="Monto interno del proyecto"
              >
                {formatInternalAmount(internalAmount)}
              </span>
            )}

            {project.status && (
              <Badge
                variant="secondary"
                className={cn(
                  "text-[10px] px-1.5 py-0 h-5 font-medium",
                  project.status === "Aprobado" &&
                    "bg-emerald-100 text-emerald-800 hover:bg-emerald-100",
                  project.status === "No aprobado" && "bg-red-100 text-red-800 hover:bg-red-100",
                )}
              >
                {project.status === "Aprobado" && <CheckCircle2 className="w-2.5 h-2.5 mr-0.5" />}
                {project.status}
              </Badge>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function formatInternalAmount(amount: number): string {
  return `$${amount.toLocaleString("en-US", {
    minimumFractionDigits: Number.isInteger(amount) ? 0 : 2,
    maximumFractionDigits: 2,
  })}`;
}

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