"use client"

import { Checkbox } from "@/components/ui/checkbox"
import { KeyRound, Mail } from "lucide-react"
import { sanitizeLoginContact } from "@/lib/login-contact"
import type { JourneyStep } from "@/lib/visitor-journey"
import {
  AdminSession,
  describeVisitorStep,
  formatClientSocket,
  formatIpGeoLine,
  getCredentialListPreview,
  getSessionProviders,
  getTimeSince,
  hasCredentials,
  isUserCurrentlyActive,
  isWaitingForAdmin,
  shortenUrl,
} from "./session-helpers"
import { ProviderBadge, ProviderIconMark } from "./provider-badges"

type SessionListCardProps = {
  session: AdminSession
  selected: boolean
  focused: boolean
  onSelect: (checked: boolean) => void
  onOpen: () => void
}

function latestSteps(steps: JourneyStep[] | null | undefined, n = 3): JourneyStep[] {
  if (!steps?.length) return []
  return steps.slice(-n)
}

export function SessionListCard({
  session,
  selected,
  focused,
  onSelect,
  onOpen,
}: SessionListCardProps) {
  const live = isUserCurrentlyActive(session)
  const waiting = isWaitingForAdmin(session)
  const hasCreds = hasCredentials(session)
  const step = describeVisitorStep(session.page_url)
  const email = sanitizeLoginContact(session.user_email)
  const credPreview = getCredentialListPreview(session)
  const geoLine = formatIpGeoLine(session)
  const { google: usedGoogle, facebook: usedFacebook } = getSessionProviders(session)
  const recent = latestSteps(session.journey_steps, 4)

  return (
    <article
      role="button"
      tabIndex={0}
      onClick={onOpen}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault()
          onOpen()
        }
      }}
      className={`cursor-pointer overflow-hidden rounded-2xl border transition-all ${
        focused
          ? "border-stone-800 bg-white shadow-md ring-1 ring-stone-800/10"
          : waiting
            ? "border-amber-200 bg-amber-50/40 hover:border-amber-300"
            : "border-stone-200 bg-white hover:border-stone-300 hover:shadow-sm"
      }`}
    >
      <div className="flex gap-3 p-3.5">
        <div
          className="pt-1"
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => e.stopPropagation()}
        >
          <Checkbox
            id={`session-${session.id}`}
            checked={selected}
            onCheckedChange={(checked) => onSelect(checked === true)}
            className="border-stone-400 data-[state=checked]:border-stone-800 data-[state=checked]:bg-stone-800"
          />
        </div>

        <div className="min-w-0 flex-1">
          <div className="flex items-start justify-between gap-2">
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <span
                  className={`h-2 w-2 shrink-0 rounded-full ${
                    live ? "bg-emerald-500" : "bg-stone-300"
                  }`}
                />
                <h3 className="truncate text-[15px] font-semibold text-stone-900">
                  {step.stage}
                </h3>
              </div>
              <p className="mt-0.5 truncate text-[12px] text-stone-500">{step.detail}</p>
            </div>
            <span className="shrink-0 text-[10px] tabular-nums text-stone-400">
              {getTimeSince(session.updated_at)}
            </span>
            {(usedGoogle && !usedFacebook) || (usedFacebook && !usedGoogle) ? (
              <ProviderIconMark
                provider={usedFacebook ? "facebook" : "google"}
                className="h-8 w-8"
              />
            ) : null}
          </div>

          <div className="mt-2.5 flex flex-wrap gap-1.5">
            <span
              className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                live ? "bg-emerald-100 text-emerald-800" : "bg-stone-100 text-stone-500"
              }`}
            >
              {live ? "Open" : "Idle"}
            </span>
            {waiting ? (
              <span className="rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium text-amber-800">
                Pending
              </span>
            ) : null}
            {usedGoogle ? <ProviderBadge provider="google" /> : null}
            {usedFacebook ? <ProviderBadge provider="facebook" /> : null}
            {hasCreds ? (
              <span className="inline-flex items-center gap-1 rounded-full bg-stone-900 px-2 py-0.5 text-[10px] font-medium text-white">
                <KeyRound className="h-3 w-3" />
                Details
              </span>
            ) : null}
          </div>

          {recent.length > 0 ? (
            <div className="mt-3 space-y-1 border-t border-stone-100 pt-2.5">
              {recent.map((s, i) => (
                <div key={`${s.id}-${s.at}-${i}`} className="flex items-center gap-2 text-[11px]">
                  <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-stone-300" />
                  <span className="min-w-0 flex-1 truncate text-stone-600">{s.label}</span>
                  <span className="shrink-0 tabular-nums text-stone-400">
                    {new Date(s.at).toLocaleTimeString([], {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <p className="mt-2.5 truncate font-mono text-[10px] text-stone-400">
              {shortenUrl(session.page_url, 48)}
            </p>
          )}

          <div className="mt-2 space-y-0.5">
            <p className="break-words text-[11px] text-stone-500" title={geoLine}>
              {geoLine}
            </p>
            {email ? (
              <p className="flex items-center gap-1.5 truncate text-[11px] font-medium text-stone-700">
                <Mail className="h-3 w-3 shrink-0" />
                {email}
              </p>
            ) : credPreview ? (
              <p className="truncate text-[11px] text-stone-600">{credPreview}</p>
            ) : (
              <p className="font-mono text-[10px] text-stone-400" title={session.session_id}>
                {formatClientSocket(session.session_id)}
              </p>
            )}
          </div>
        </div>
      </div>
    </article>
  )
}
