"use client";

import { motion } from "framer-motion";
import { useEffect, useRef, useState } from "react";

type Step =
  | { type: "command"; text: string }
  | { type: "log"; text: string }
  | { type: "progress"; text: string };

const steps: Step[] = [
  { type: "command", text: "git clone fikri-erp" },
  { type: "command", text: "cd fikri-erp" },
  { type: "command", text: "docker build -t fikri-erp ." },
  { type: "log", text: "building docker image..." },
  { type: "progress", text: "docker build" },
  { type: "log", text: "✓ docker image built successfully" },
  { type: "command", text: "docker-compose up -d" },
  { type: "log", text: "starting postgres container..." },
  { type: "log", text: "✓ postgres container running" },
  { type: "log", text: "starting api container..." },
  { type: "log", text: "✓ application deployed successfully" },
  { type: "log", text: "✓ ready on https://fikri-erp.com" },
];

export default function TerminalWindow() {
  const [lines, setLines] = useState<string[]>([]);
  const [typing, setTyping] = useState("");
  const [stepIndex, setStepIndex] = useState(0);

  const containerRef = useRef<HTMLDivElement>(null);

  const step = steps[stepIndex];

  useEffect(() => {
    if (!step) return;

    if (step.type === "command") {
      let i = 0;

      const interval = setInterval(() => {
        setTyping(step.text.slice(0, i + 1));
        i++;

        if (i === step.text.length) {
          clearInterval(interval);

          setTimeout(() => {
            setLines((prev) => [...prev, `$ ${step.text}`]);
            setTyping("");
            setStepIndex((s) => s + 1);
          }, 700);
        }
      }, 45);

      return () => clearInterval(interval);
    }

    if (step.type === "log") {
      const timeout = setTimeout(() => {
        setLines((prev) => [...prev, step.text]);
        setStepIndex((s) => s + 1);
      }, 800);

      return () => clearTimeout(timeout);
    }

    if (step.type === "progress") {
      let progress = 0;

      const interval = setInterval(() => {
        progress += 10;

        setTyping(
          `${step.text} [${"█".repeat(progress / 10)}${" ".repeat(
            10 - progress / 10
          )}] ${progress}%`
        );

        if (progress === 100) {
          clearInterval(interval);

          setTimeout(() => {
            setLines((prev) => [...prev, typing]);
            setTyping("");
            setStepIndex((s) => s + 1);
          }, 400);
        }
      }, 120);

      return () => clearInterval(interval);
    }
  }, [stepIndex]);

  useEffect(() => {
    containerRef.current?.scrollTo({
      top: containerRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [lines, typing]);

  // loop animation
  useEffect(() => {
    if (stepIndex >= steps.length) {
      const reset = setTimeout(() => {
        setLines([]);
        setTyping("");
        setStepIndex(0);
      }, 2500);

      return () => clearTimeout(reset);
    }
  }, [stepIndex]);

  return (
    <div className="w-[320px] h-[200px] rounded-lg border border-border bg-surface-elevated shadow-xl overflow-hidden font-mono">

      {/* window header */}
      <div className="flex items-center px-2 py-1.5 border-b border-border bg-surface-elevated/70">
        <div className="flex gap-1.5">
          <div className="w-2 h-2 bg-red-500 rounded-full"/>
          <div className="w-2 h-2 bg-yellow-500 rounded-full"/>
          <div className="w-2 h-2 bg-green-500 rounded-full"/>
        </div>

        <span className="ml-2 text-xs text-foreground-muted">
          fikri@dev-terminal
        </span>
      </div>

      {/* tabs */}
      <div className="flex gap-1.5 px-2 py-1 border-b border-border bg-surface-elevated/50 text-xs text-foreground-muted">
        <div className="px-1.5 py-0.5 bg-surface-elevated rounded text-accent">bash</div>
        <div className="px-1.5 py-0.5 hover:bg-surface-elevated rounded text-foreground-subtle">server</div>
        <div className="px-1.5 py-0.5 hover:bg-surface-elevated rounded text-foreground-subtle">logs</div>
      </div>

      {/* terminal body */}
      <div
        ref={containerRef}
        className="p-2 text-xs text-foreground h-[150px] overflow-hidden space-y-0.5"
      >
        {lines.map((line, i) => (
          <div key={i}>{line}</div>
        ))}

        {typing && (
          <div className="flex">
            <span>{typing}</span>

            <motion.span
              animate={{ opacity: [0, 1, 0] }}
              transition={{ repeat: Infinity, duration: 1 }}
              className="ml-1"
            >
              |
            </motion.span>
          </div>
        )}
      </div>
    </div>
  );
}