"use client";

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

// 📌 نوع داده‌های فرم
interface ProjectFormData {
  userId: string | null;
  expertise: string | null;
  subExpertise: string[];
  gender: string;
  age: string;
  publicType: string;
  stateId: string;
  cityId: string;
  projTitle: string;
  projectTime: string;
  offerPrice: string;
  description: string;
  numberOfPerson: string;
  selectedType: string;
  price2: string;
  _id: string;
}

// 📌 مقدار اولیه فرم
const initialFormData: ProjectFormData = {
  expertise: null,
  subExpertise: [],
  gender: "",
  age: "",
  publicType: "",
  stateId: "",
  cityId: "",
  projTitle: "",
  projectTime: "",
  offerPrice: "",
  description: "",
  numberOfPerson: "",
  selectedType: "normal",
  price2: "",
  userId: null,
  _id: "",
};

// 📌 ایجاد Context
const ProjectFormContext = createContext<{
  formData: ProjectFormData;
  updateForm: (data: Partial<ProjectFormData>) => void;
  resetForm: () => void;
  setIsEditing: (editing: boolean) => void;
  isEditing: boolean;
}>(null!);

// 📌 Provider برای فرم
export const ProjectFormProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [isEditing, setIsEditing] = useState(false);
  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 data;
        } else {
          localStorage.removeItem("projectForm");
        }
      }
    }
    return initialFormData;
  });

  // 📌 ذخیره فرم در localStorage
  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(initialFormData);
    localStorage.removeItem("projectForm");
  };

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

// 📌 هوک برای استفاده از فرم
export const useProjectForm = () => {
  return useContext(ProjectFormContext);
};
