"use client"

import Image from "next/image";
import { useState } from "react";
import MemberForm from "@/components/forms/MemberForm";
import EventForm from "./forms/EventForm";
import VisitorForm from "./forms/VisitorForm";
import CellGroupForm from "./forms/CellGroupForm";
import PrayerRequestForm from "./forms/PrayerForm";
import InquiryForm from "./forms/InquiryForm";

const forms: {
  [key: string]: (type: "create" | "update", data?: any) => JSX.Element;
} = {
  Members: (type, data) => <MemberForm type={type} data={data} />,
  Events: (type, data) => <EventForm type={type} data={data} />,
  Visitors: (type, data) => <VisitorForm type={type} data={data} />,
  CellGroup: (type, data) => <CellGroupForm type={type} data={data} />,
  PrayerRequest: (type, data) => <PrayerRequestForm type={type} data={data} />,
  Inquiries: (type, data) => <InquiryForm type={type} data={data} />,

};

const FormModal = ({
    table,
    type,
    data,
    id,
}:{
    table:
    | "Events" 
    | "Visitors" 
    | "CellGroup" 
    | "PrayerRequest" 
    | "Members" 
    | "Inquiries";
    type: "create"|"update"|"delete";
    data?: any;
    id?: number;
}) => {
  const size = type === "create" ? "w-6 h-6" : "w-6 h-6";
  const bgColor = 
  type === "create"
  ? "bg-red-300" 
  : type ==="update"
  ? "bg-green-500" 
  : "bg-red-700";

  const [open, setOpen] = useState(false);

  const Form = ()=> {
    return type === "delete" && id? ( 
    <form action="" className="p-4 flex flex-col gap-4">
        <span className="text-center font-medium">All data will be lost. Are you sure you want to delete this {table}?</span>
        <button className="bg-red-700 text-white py-2 px-4 rounded-md border-none w-max self-center">Delete</button>
    </form> 
    ): type ==="create" || type ==="update"? ( 
     forms[table](type, data)
    ) : (
      "Form not found!" 
    );
  };

  return (
  <>
   <button 
     className= {`${size} flex items-center justify-center rounded-full ${bgColor}`}
     onClick={()=>setOpen(true)} 
    >
     <Image src={`/${type}.png`} alt="" width={14} height={14} />
   </button>
   {open &&(
       <div className="w-screen h-screen absolute left-0 top-0 bg-black bg-opacity-60 z-50 flex items-center justify-center">
           <div className="bg-white p-4 rounded-md relative w-[90%] md:w-[70%] lg:w-[60%] xl:w-[50%] 2xl:w-[40%]">
            <Form/>
               <div
                 className="absolute top-4 right-4 cursor-pointer"
                 onClick={() => setOpen(false)}
                >
                <Image src="/close.png" alt="" width={14} height={14} />
            </div>
        </div>
    </div>
   )}
  </>
  );
};

export default FormModal;