import { forwardRef, useEffect, useRef, useState } from "react";
import {
  Bot,
  Sparkles,
  FileText,
  Globe,
  BookOpen,
  Database,
} from "lucide-react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Terminal, AnimatedStep } from "@/components/ui/terminal";
import { TypingAnimation } from "@/components/ui/typing-animation";
import { AnimatedBeam } from "@/components/ui/animated-beam";
import { cn } from "@/lib/utils";

const GERAR_PARECER_STEPS = [
  "Pesquisando fontes jurídicas confiáveis...",
  "Analisando documentação e anexos...",
  "Consultando jurisprudência e decisões correlatas...",
  "Verificando legislação vigente e súmulas...",
  "Identificando fundamentação legal aplicável...",
  "Estruturando argumentação...",
  "Elaborando conclusões...",
  "Revisando citações e referências...",
  "Consolidando fundamentos e redigindo parecer...",
  "Estruturando parecer...",
] as const;

const STEP_COUNT = GERAR_PARECER_STEPS.length;
const STEP_INTERVAL_MS = 1500;

export interface ParecerJuridicoGeneratingScreenProps {
  progress?: number;
  message?: string;
}

function visibleLineCountFromProgress(progress: number): number {
  if (progress <= 0) return 1;
  const phase = (progress / 100) * STEP_COUNT;
  const stepInCycle = Math.floor(phase) % STEP_COUNT;
  return Math.min(stepInCycle + 1, STEP_COUNT);
}

const BeamCircle = forwardRef<
  HTMLDivElement,
  { className?: string; children?: React.ReactNode }
>(({ className, children }, ref) => (
  <div
    ref={ref}
    className={cn(
      "z-10 flex size-12 items-center justify-center rounded-full border-2 border-slate-300 bg-slate-100 text-slate-700 shadow-sm",
      className
    )}
  >
    {children}
  </div>
));
BeamCircle.displayName = "BeamCircle";

function GoogleIcon({ className }: { className?: string }) {
  return (
    <svg
      className={cn("size-6", className)}
      viewBox="0 0 24 24"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
        fill="#4285F4"
      />
      <path
        d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
        fill="#34A853"
      />
      <path
        d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
        fill="#FBBC05"
      />
      <path
        d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
        fill="#EA4335"
      />
    </svg>
  );
}

export function ParecerJuridicoGeneratingScreen({
  progress,
  message = "Assim que finalizar, o modal será fechado automaticamente.",
}: ParecerJuridicoGeneratingScreenProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const sparklesRef = useRef<HTMLDivElement>(null);
  const fileRef = useRef<HTMLDivElement>(null);
  const globeRef = useRef<HTMLDivElement>(null);
  const centerRef = useRef<HTMLDivElement>(null);
  const googleRef = useRef<HTMLDivElement>(null);
  const bookRef = useRef<HTMLDivElement>(null);
  const dbRef = useRef<HTMLDivElement>(null);

  const [loopStep, setLoopStep] = useState(0);
  useEffect(() => {
    if (progress !== undefined) return;
    const id = setInterval(() => {
      setLoopStep((s) => (s + 1) % STEP_COUNT);
    }, STEP_INTERVAL_MS);
    return () => clearInterval(id);
  }, [progress]);

  const visibleCount =
    progress !== undefined
      ? visibleLineCountFromProgress(progress)
      : loopStep + 1;

  return (
    <Dialog open>
      <DialogContent
        hideClose
        overlayClassName="bg-black/50"
        className="max-w-2xl gap-0 overflow-hidden bg-white p-0 sm:rounded-xl"
      >
        <div className="flex flex-col gap-4 p-5">
          <div className="flex items-center gap-3 rounded-t-lg border border-b-0 border-border bg-zinc-100 px-3 py-2.5">
            <div className="flex gap-1.5">
              <span className="size-3 rounded-full bg-[#ff5f57]" aria-hidden />
              <span className="size-3 rounded-full bg-[#febc2e]" aria-hidden />
              <span className="size-3 rounded-full bg-[#28c840]" aria-hidden />
            </div>
            <span className="font-mono text-xs text-muted-foreground">
              codex parecer — gerando
            </span>
          </div>

          <Terminal className="min-h-[200px] space-y-2 rounded-t-none border-t-0 bg-white p-4 font-mono text-sm">
            <AnimatedStep delay={0} className="text-muted-foreground">
              &gt; codex parecer --generate
            </AnimatedStep>
            {GERAR_PARECER_STEPS.slice(0, visibleCount).map((text, i) => (
              <div key={`${visibleCount}-${i}-${text}`} className="flex items-center gap-0">
                {i < visibleCount - 1 ? (
                  <span className="text-green-600 dark:text-green-400">
                    ✔ {text}
                  </span>
                ) : (
                  <TypingAnimation
                    key={`typing-${visibleCount}`}
                    startOnView={false}
                    showCursor
                    cursorStyle="block"
                    className="text-green-600 dark:text-green-400"
                  >
                    {`✔ ${text}`}
                  </TypingAnimation>
                )}
              </div>
            ))}
          </Terminal>

          <p className="text-center text-sm text-muted-foreground">
            {message ?? "A geração pode levar de 5 a 8 minutos. Mantenha esta tela aberta até finalizar."}
          </p>

          <div className="rounded-xl border border-border bg-white p-6">
            <div
              ref={containerRef}
              className="relative flex h-[260px] w-full items-center justify-center overflow-hidden"
            >
              <div className="flex size-full max-h-[220px] max-w-lg flex-col items-stretch justify-between">
                <div className="flex flex-row items-center justify-between">
                  <BeamCircle ref={sparklesRef}>
                    <Sparkles className="size-6 text-amber-400" />
                  </BeamCircle>
                  <BeamCircle ref={fileRef}>
                    <FileText className="size-6 text-slate-600" />
                  </BeamCircle>
                </div>
                <div className="flex flex-row items-center justify-between">
                  <BeamCircle ref={globeRef}>
                    <Globe className="size-6 text-sky-400" />
                  </BeamCircle>
                  <BeamCircle ref={centerRef} className="size-14 border-slate-400 bg-slate-200">
                    <Bot className="size-8 text-slate-700" />
                  </BeamCircle>
                  <BeamCircle ref={googleRef}>
                    <GoogleIcon className="size-6" />
                  </BeamCircle>
                </div>
                <div className="flex flex-row items-center justify-between">
                  <BeamCircle ref={bookRef}>
                    <BookOpen className="size-6 text-slate-600" />
                  </BeamCircle>
                  <BeamCircle ref={dbRef}>
                    <Database className="size-6 text-slate-600" />
                  </BeamCircle>
                </div>
              </div>

              <AnimatedBeam
                containerRef={containerRef}
                fromRef={sparklesRef}
                toRef={centerRef}
                curvature={-75}
                endYOffset={-10}
                gradientStartColor="#f59e0b"
                gradientStopColor="#64748b"
              />
              <AnimatedBeam
                containerRef={containerRef}
                fromRef={fileRef}
                toRef={centerRef}
                curvature={-75}
                endYOffset={-10}
                reverse
                gradientStartColor="#94a3b8"
                gradientStopColor="#64748b"
              />
              <AnimatedBeam
                containerRef={containerRef}
                fromRef={globeRef}
                toRef={centerRef}
                gradientStartColor="#0ea5e9"
                gradientStopColor="#64748b"
              />
              <AnimatedBeam
                containerRef={containerRef}
                fromRef={googleRef}
                toRef={centerRef}
                reverse
                gradientStartColor="#64748b"
                gradientStopColor="#94a3b8"
              />
              <AnimatedBeam
                containerRef={containerRef}
                fromRef={bookRef}
                toRef={centerRef}
                curvature={75}
                endYOffset={10}
                gradientStartColor="#94a3b8"
                gradientStopColor="#64748b"
              />
              <AnimatedBeam
                containerRef={containerRef}
                fromRef={dbRef}
                toRef={centerRef}
                curvature={75}
                endYOffset={10}
                reverse
                gradientStartColor="#94a3b8"
                gradientStopColor="#64748b"
              />
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
