"use client";

import { createPrayers, updatePrayers } from "../../../lib/api";

import Image from "next/image";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

const schema = z.object({
  requestId: z.string().min(1, { message: "Request ID is required!" }),
  memberName: z
    .string()
    .min(1, { message: "The name of the member is required!" }),
  description: z
    .string()
    .min(1, { message: "Description of the prayer request is required!" }),
  status: z.string().min(1, { message: "Status of the request is required!" }),
});

type Inputs = z.infer<typeof schema>;

const PrayerRequestForm = ({
  type,
  data,
}: {
  type: "create" | "update";
  data?: any;
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>({
    resolver: zodResolver(schema),
    defaultValues: {
      requestId: type === "update" ? data?.requestId : "",
      memberName: type === "update" ? data?.memberName : "",
      description: type === "update" ? data?.description : "",
      status: type === "update" ? data?.status : "Pending",
    },
  });

  const onSubmit = handleSubmit(async (formData) => {
    try {
      if (type === "create") {
        await createPrayers(formData);
        alert("Prayer request created successfully!");
      } else if (type === "update") {
        await updatePrayers(data.requestId, formData);
        alert("Prayer request updated successfully!");
      }
    } catch (err) {
      console.error("Error submitting prayer request:", err);
      alert("Failed to submit prayer request. Please try again.");
    }
  });

  return (
    <form
      className="flex flex-col gap-6 p-6 bg-white rounded-md shadow-md"
      onSubmit={onSubmit}
    >
      <h1 className="text-2xl font-semibold text-gray-700">
        {type === "create" ? "Create" : "Update"} Prayer Request
      </h1>

      <div className="text-sm text-gray-500 font-medium">
        Personal Information
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Request ID */}
        <div className="flex flex-col">
          <label className="text-sm font-medium mb-1">Request ID</label>
          <input
            type="text"
            {...register("requestId")}
            className="border p-2 rounded-md"
            disabled={type === "update"} // disable for update mode
          />
          {errors.requestId && (
            <span className="text-red-500 text-xs mt-1">
              {errors.requestId.message}
            </span>
          )}
        </div>

        {/* Member Name */}
        <div className="flex flex-col">
          <label className="text-sm font-medium mb-1">Member Name</label>
          <input
            type="text"
            {...register("memberName")}
            className="border p-2 rounded-md"
          />
          {errors.memberName && (
            <span className="text-red-500 text-xs mt-1">
              {errors.memberName.message}
            </span>
          )}
        </div>

        {/* Description */}
        <div className="flex flex-col md:col-span-2">
          <label className="text-sm font-medium mb-1">Description</label>
          <textarea
            rows={4}
            {...register("description")}
            className="border p-2 rounded-md"
          />
          {errors.description && (
            <span className="text-red-500 text-xs mt-1">
              {errors.description.message}
            </span>
          )}
        </div>

        {/* Status Dropdown */}
        <div className="flex flex-col">
          <label className="text-sm font-medium mb-1">Status</label>
          <select
            {...register("status")}
            className="border p-2 rounded-md"
            defaultValue={data?.status || "Pending"}
          >
            <option value="Pending">Pending</option>
            <option value="Answered">Answered</option>
            <option value="In Progress">In Progress</option>
            <option value="Closed">Closed</option>
          </select>
          {errors.status && (
            <span className="text-red-500 text-xs mt-1">
              {errors.status.message}
            </span>
          )}
        </div>
      </div>

      <button
        type="submit"
        className="mt-4 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition"
      >
        {type === "create" ? "Create Request" : "Update Request"}
      </button>
    </form>
  );
};

export default PrayerRequestForm;
