"use client";

import { createContext, useContext, useEffect, useState } from "react";

export type ProjectRoleForm = {
  id: string;
  expertise: string;
  subExpertise: string[];
  numberOfPerson: string;
  heightMin: string;
  heightMax: string;
  weightMin: string;
  weightMax: string;
  sizeMin: string;
  sizeMax: string;
  eyeColor: string;
  hairColor: string;
  portfolioRequired: boolean;
};

export interface ProjectFormData {
  userId: string | null;
  expertise: string | null;
  subExpertise: string[];
  gender: string;
  age: string;
  ageMin: string;
  ageMax: string;
  publicType: string;
  stateId: string;
  cityId: string;
  neighborhood: string;
  address: string;
  markerCoordinate: number[];
  projTitle: string;
  projectTime: string;
  offerPrice: string;
  description: string;
  numberOfPerson: string;
  selectedType: string;
  price2: string;
  paymentMethod: string;
  startDate: string;
  workHoursStart: string;
  workHoursEnd: string;
  collaborationType: string;
  experience: string;
  roles: ProjectRoleForm[];
  _id: string;
}

export const initialProjectFormData: ProjectFormData = {
  expertise: null,
  subExpertise: [],
  gender: "",
  age: "",
  ageMin: "",
  ageMax: "",
  publicType: "",
  stateId: "",
  cityId: "",
  neighborhood: "",
  address: "",
  markerCoordinate: [],
  projTitle: "",
  projectTime: "",
  offerPrice: "",
  description: "",
  numberOfPerson: "",
  selectedType: "normal",
  price2: "",
  paymentMethod: "",
  startDate: "",
  workHoursStart: "",
  workHoursEnd: "",
  collaborationType: "",
  experience: "",
  roles: [],
  userId: null,
  _id: "",
};

const ProjectFormContext = createContext<{
  formData: ProjectFormData;
  updateForm: (data: Partial<ProjectFormData>) => void;
  resetForm: () => void;
  setIsEditing: (editing: boolean) => void;
  isEditing: boolean;
  draftId: string | null;
  setDraftId: (id: string | null) => void;
}>(null!);

export const ProjectFormProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [draftId, setDraftId] = useState<string | null>(null);
  const [formData, setFormData] = useState<ProjectFormData>(() => {
    if (typeof window !== "undefined" && !isEditing) {
      const storedData = localStorage.getItem("projectForm");
      if (storedData) {
        const { data, timestamp } = JSON.parse(storedData);
        const now = new Date().getTime();
        if (now - timestamp < 10 * 60 * 1000) {
          return {
            ...initialProjectFormData,
            ...data,
            roles: data.roles || [],
          };
        }
        localStorage.removeItem("projectForm");
      }
    }
    return initialProjectFormData;
  });

  useEffect(() => {
    if (!isEditing) {
      const dataToStore = {
        data: formData,
        timestamp: new Date().getTime(),
      };
      localStorage.setItem("projectForm", JSON.stringify(dataToStore));
    }
  }, [formData, isEditing]);

  const updateForm = (data: Partial<ProjectFormData>) => {
    setFormData((prev) => ({ ...prev, ...data }));
  };

  const resetForm = () => {
    setFormData(initialProjectFormData);
    setDraftId(null);
    localStorage.removeItem("projectForm");
  };

  return (
    <ProjectFormContext.Provider
      value={{
        formData,
        updateForm,
        resetForm,
        setIsEditing,
        isEditing,
        draftId,
        setDraftId,
      }}
    >
      {children}
    </ProjectFormContext.Provider>
  );
};

export const useProjectForm = () => {
  return useContext(ProjectFormContext);
};
