import { create } from "zustand"
import { persist } from "zustand/middleware"
import { Lesson } from "../components/LessonItem"
import { ParsedFile } from "../components/FileUploader"
import { TMessage } from "../components/Message"
// import { ParsedLink } from "../components/LinkUploader"

export type FormState = {
  description: string
  duration: number
  hasContentIndex: boolean
  contentIndex: string
  purpose: string
  language?: string
  isCompleted: boolean
  variables: string[]
  currentStep: string
  title?: string
  technologies?: string[]
}

type Auth = {
  bcToken: string
  rigoToken: string
  userId: string
  user: any
  publicToken: string
}
export type Syllabus = {
  lessons: Lesson[]
  courseInfo: FormState
  // messages: TMessage[]
}

type Consumables = {
  [key: string]: number
}

type TTechnology = {
  slug: string
  lang: string
}

type Store = {
  auth: Auth
  formState: FormState
  setFormState: (formState: Partial<FormState>) => void
  resetFormState: () => void
  setAuth: (auth: Auth) => void
  // syllabus: Syllabus
  planToRedirect: string
  setPlanToRedirect: (planToRedirect: string) => void
  uploadedFiles: ParsedFile[]
  setUploadedFiles: (uploadedFiles: ParsedFile[]) => void
  messages: TMessage[]
  setMessages: (messages: TMessage[]) => void
  cleanHistory: () => void
  history: Syllabus[]
  technologies: TTechnology[]
  setTechnologies: (technologies: TTechnology[]) => void
  undo: () => void
  push: (syllabus: Syllabus) => void
  cleanAll: () => void
  // setSyllabus: (syllabus: Partial<Syllabus>) => void
  consumables: Consumables
  setConsumables: (consumables: Partial<Consumables>) => void
  mode: "student" | "teacher"
  setMode: (mode: "student" | "teacher") => void
}

const useStore = create<Store>()(
  persist(
    (set) => ({
      auth: {
        bcToken: "",
        rigoToken: "",
        userId: "",
        user: null,
        publicToken: "",
      },
      planToRedirect: "learnpack-creator",
      setPlanToRedirect: (planToRedirect: string) => set({ planToRedirect }),
      formState: {
        description: "",
        duration: 0,
        hasContentIndex: false,
        contentIndex: "",
        purpose: "",
        language: "en",
        technologies: [],
        // sources: [],
        isCompleted: false,
        currentStep: "description",
        variables: [
          "description",
          "duration",
          "purpose",
          "hasContentIndex",
          "verifyHuman",
        ],
      },
      messages: [],
      technologies: [],
      setTechnologies: (technologies: TTechnology[]) => set({ technologies }),
      setMessages: (messages: TMessage[]) => set({ messages }),
      setFormState: (formState: Partial<FormState>) =>
        set((state) => ({ formState: { ...state.formState, ...formState } })),
      resetFormState: () =>
        set({
          formState: {
            currentStep: "description",
            description: "",
            duration: 0,
            language: "en",
            technologies: [],
            hasContentIndex: false,
            contentIndex: "",
            purpose: "",
            isCompleted: false,
            variables: [
              "description",
              "duration",
              "purpose",
              "hasContentIndex",
              "verifyHuman",
            ],
          },
        }),

      setUploadedFiles: (uploadedFiles) =>
        set(() => ({
          uploadedFiles: [...uploadedFiles],
        })),
      uploadedFiles: [],
      history: [],
      push: (syllabus: Syllabus) => {
        set((state) => ({
          history: [...state.history, syllabus],
        }))
      },

      undo: () => {
        set((state) => {
          return {
            history: state.history.slice(0, -1),
          }
        })
      },
      cleanHistory: () => {
        set(() => ({ history: [] }))
      },
      cleanAll: () => {
        set({
          uploadedFiles: [],
          messages: [],
          history: [],
          technologies: [],
          formState: {
            description: "",
            duration: 0,

            language: "en",
            technologies: [],
            hasContentIndex: false,
            contentIndex: "",
            purpose: "",
            isCompleted: false,
            variables: [
              "description",
              "duration",
              "purpose",
              "hasContentIndex",
              "verifyHuman",
            ],
            currentStep: "description",
          },
        })
      },
      consumables: {},
      setConsumables: (consumables: Partial<Consumables>) =>
        set((state) => {
          const sanitized: Consumables = Object.fromEntries(
            Object.entries(consumables).map(([k, v]) => [k, v ?? 0])
          )
          return {
            consumables: {
              ...state.consumables,
              ...sanitized,
            },
          }
        }),

      setAuth: (auth: Auth) => set({ auth }),
      mode: "student",
      setMode: (mode: "student" | "teacher") => set({ mode }),
    }),
    {
      name: "syllabus-storage",
    }
  )
)

export default useStore
