"use client";

import React, { createContext, useContext, useEffect, useState, useMemo } from "react";
import type { Experience, MiniProject, Project, RealWork, Skill } from "../types";

interface ProfileContextType {
  status: string;
  statusMessage: string;
  borderStatus: string;
  glowColor: string;
  displayMessage: string;
  isScrambling: boolean;
  rotatingMessages: string[];
  projects: Project[];
  miniProjects: MiniProject[];
  experiences: Experience[];
  realWork: RealWork[];
  skills: Skill[];
  selectedMiniProject: MiniProject | null;
  setSelectedMiniProject: (p: MiniProject | null) => void;
  selectedExperience: Experience | null;
  setSelectedExperience: (e: Experience | null) => void;
}

const ProfileContext = createContext<ProfileContextType | undefined>(undefined);

export function ProfileProvider({ children }: { children: React.ReactNode }) {
  const [status, setStatus] = useState("");
  const [borderStatus, setBorderStatus] = useState("border-gray-700");
  const [glowColor, setGlowColor] = useState("rgba(55, 65, 81, 0.5)");
  const [statusMessage, setStatusMessage] = useState("[??????]");
  const [messageIndex, setMessageIndex] = useState(0);
  const [displayMessage, setDisplayMessage] = useState("");
  const [isScrambling, setIsScrambling] = useState(false);

  const [selectedMiniProject, setSelectedMiniProject] = useState<MiniProject | null>(null);
  const [selectedExperience, setSelectedExperience] = useState<Experience | null>(null);

  const [projects, setProjects] = useState<Project[]>([]);
  const [miniProjects, setMiniProjects] = useState<MiniProject[]>([]);
  const [experiences, setExperiences] = useState<Experience[]>([]);
  const [realWork, setRealWork] = useState<RealWork[]>([]);
  const [skills, setSkills] = useState<Skill[]>([]);

  const rotatingMessages = useMemo(
    () => [
      "Yelling at Luna",
      "Assigning more Issues to myself and letting Luna do them",
      "NOT coding in Rust 😂✌️",
      "Rewriting the same helper 3 times",
      "Micro-service-maxxing",
      "Blaming SHSF for my bad code",
      "Shipping fast SHSF code",
      "Writing code with 1.4k+ Lines",
      "Love-Hate relationship with TypeScript",
      "Blaming Openai",
      "Undescribable Music Taste"
    ],
    [],
  );

  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{}|;:',.<>?/`~" +
    "?????????????????????????";

  useEffect(() => {
    if (status === "online") {
      setBorderStatus("border-green-500");
      setGlowColor("rgba(34, 197, 94, 0.5)");
      setStatusMessage("Reachable");
    } else if (status === "offline") {
      setBorderStatus("border-gray-500");
      setGlowColor("rgba(107, 114, 128, 0.5)");
      setStatusMessage("Probably Away");
    } else if (status === "dnd") {
      setBorderStatus("border-red-600");
      setGlowColor("rgba(220, 38, 38, 0.5)");
      setStatusMessage("Not Reachable");
    } else if (status === "idle") {
      setBorderStatus("border-yellow-500");
      setGlowColor("rgba(234, 179, 8, 0.5)");
      setStatusMessage("Doing anything but work");
    } else {
      setBorderStatus("border-gray-700");
      setGlowColor("rgba(55, 65, 81, 0.5)");
      setStatusMessage("[??????]");
    }
  }, [status]);

  useEffect(() => {
    fetch("https://shsf-api.reversed.dev/api/exec/6/c084ec4a-1b20-491e-ab2e-67c5fa8881e6")
      .then((res) => res.json())
      .then((data) => setStatus(data.status))
      .catch(() => setStatus("offline"));

    const fetchRealWork = async () => {
      try {
        const res = await fetch("https://shsf-api.reversed.dev/api/exec/4/e942538c-caa1-49d1-8953-dfab1e62f8cb/real_work");
        if (res.ok) setRealWork(await res.json());
      } catch { setRealWork([]); }
    };
       
    fetch("https://shsf-api.reversed.dev/api/exec/4/e942538c-caa1-49d1-8953-dfab1e62f8cb/projects")
      .then(res => res.json()).then(setProjects).catch(() => setProjects([]));
    fetch("https://shsf-api.reversed.dev/api/exec/4/e942538c-caa1-49d1-8953-dfab1e62f8cb/mini_projects")
      .then(res => res.json()).then(setMiniProjects).catch(() => setMiniProjects([]));
    fetch("https://shsf-api.reversed.dev/api/exec/4/e942538c-caa1-49d1-8953-dfab1e62f8cb/experience")
      .then(res => res.json()).then(setExperiences).catch(() => setExperiences([]));
    fetch("https://shsf-api.reversed.dev/api/exec/4/e942538c-caa1-49d1-8953-dfab1e62f8cb/skills")
      .then(res => res.json()).then(setSkills).catch(() => setSkills([]));

    fetchRealWork();
  }, []);

  useEffect(() => {
    const targetMessage = rotatingMessages[messageIndex];
    if (isScrambling) {
      let iteration = 0;
      const interval = setInterval(() => {
        setDisplayMessage(targetMessage.split("").map((char, i) => {
          if (i < iteration) return targetMessage[i];
          if (char === " " || /[\u{1F000}-\u{1F9FF}]/u.test(char)) return char;
          return characters[Math.floor(Math.random() * characters.length)];
        }).join(""));
        if (iteration >= targetMessage.length) {
          clearInterval(interval);
          setIsScrambling(false);
        }
        iteration += 1;
      }, 15);
      return () => clearInterval(interval);
    } else {
      setDisplayMessage(targetMessage);
    }
  }, [messageIndex, isScrambling, characters, rotatingMessages]);

  useEffect(() => {
    const interval = setInterval(() => {
      setIsScrambling(true);
      setMessageIndex((prev) => (prev + 1) % rotatingMessages.length);
    }, 7000);
    return () => clearInterval(interval);
  }, [rotatingMessages.length]);

  const value = {
    status, statusMessage, borderStatus, glowColor, displayMessage, isScrambling,
    rotatingMessages,
    projects, miniProjects, experiences, realWork, skills,
    selectedMiniProject, setSelectedMiniProject,
    selectedExperience, setSelectedExperience
  };

  return <ProfileContext.Provider value={value}>{children}</ProfileContext.Provider>;
}

export function useProfile() {
  const context = useContext(ProfileContext);
  if (context === undefined) throw new Error("useProfile must be used within a ProfileProvider");
  return context;
}
