"use client";

import { IFeature, Service } from "@/types/types";
import { createContext, useContext, useEffect, useState } from "react";

interface BillboardFormData {
  stateId: string | null;
  cityId: string | null;
  categoryId: string;
  adsTitle: string;
  description: string | null;
  neighbourhood: string | null;
  address: string | null;
  markerCoordinate: string[] | [] | null;
  images: string[];
  services: Service[];
  selectedFeatures: IFeature[];
  landline: string | null;
  mobile: string | null;
  telegram: string | null;
  whatsapp: string | null;
  instagram: string | null;
  saveData: boolean | null;
  selectedType: string;
  showDiscount: null | boolean;
  _id?: string;
}

const initialFormData: BillboardFormData = {
  stateId: "",
  cityId: "",
  categoryId: "",
  adsTitle: "",
  description: "",
  neighbourhood: "",
  address: "",
  markerCoordinate: [],
  images: [],
  services: [],
  selectedFeatures: [],
  landline: "",
  mobile: "",
  telegram: "",
  whatsapp: "",
  instagram: "",
  saveData: null,
  selectedType: "",
  showDiscount: false,
  _id: "",
};

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

export const BillboardFormProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState<BillboardFormData>(() => {
    if (typeof window !== "undefined" && !isEditing) {
      const storedData = localStorage.getItem("billboardForm");
      if (storedData) {
        const { data, timestamp } = JSON.parse(storedData);
        const now = new Date().getTime();
        if (now - timestamp < 3 * 60 * 1000) {
          return data;
        } else {
          localStorage.removeItem("billboardForm");
        }
      }
    }
    return initialFormData;
  });

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

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

  const resetForm = () => {
    setFormData(initialFormData);
    localStorage.removeItem("billboardForm");
  };

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

export const useBillboardForm = () => {
  return useContext(BillboardFormContext);
};
