"use client";

import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

import Form from "@/src/components/admin/form/Form";
import FormGroup from "@/src/components/admin/form/FormGroup";
import Label from "@/src/components/admin/form/Label";
import Input from "@/src/components/admin/form/input/InputField";

import { useToastMessage } from "@/src/hooks/admin/useToastMessage";
import { useStateContext } from "@/src/context/admin/StateContext";
import { useRouter, useParams } from "next/navigation";
import Select from "@/src/components/admin/form/Select";
import FileInput from "@/src/components/admin/form/input/FileInput";
import { useState } from "react";
import Radio from "@/src/components/admin/form/input/Radio";
import { useLabeledOptions } from "@/src/hooks/admin/useFetchOptions";
import { getAllDepartment, getAllDesignations } from "@/src/services/admin/services";


const userInquirySchema = z.object({
  full_name: z.string().min(1, "Full Name is required"),
  contact_no: z.string().min(10, "Contact number must be at least 10 digits"),
  email: z.string().email("Invalid email address").min(1, "Email is required"),
  address: z.string().min(1, "Address is required"),
  designation: z.string().min(1, "designation is required"),
  department: z.string().min(1, "department is required"),
  image: z
    .any()
    .refine((files) => files && files.length > 0, {
      message: "Govt Id Card is required",
    }),
  gender: z.enum(["male", "female"]).refine((val) => !!val, {
    message: "Gender is required",
  }),
});

type UserInquiryFormData = z.infer<typeof userInquirySchema>;

export default function UserInquiryForm() {
  const { message, setMessage } = useToastMessage();
  const { refresh, setRefresh } = useStateContext();
  const router = useRouter();
  const params = useParams();
  const itemID = Array.isArray(params.id) ? params.id[0] : params.id;
  const isEdit = itemID !== undefined && itemID !== null;

  const [imagePreview, setImagePreview] = useState<string | null>(null);


  const { options: designationOptions } = useLabeledOptions<{ id: number; designation_name: string; }>({
    fetchService: async () => {
      const res = await getAllDesignations();
      return res.data.data;
    },
    mapLabel: (item) => item.designation_name,
    mapValue: (item) => item.id,
    onError: (err) => console.error(err),

  });

  const { options: departmentOptions } = useLabeledOptions<{ id: number; department_name: string; }>({
    fetchService: async () => {
      const res = await getAllDepartment();
      return res.data.data;
    },
    mapLabel: (item) => item.department_name,
    mapValue: (item) => item.id,
    onError: (err) => console.error(err),

  });

  const {
    register,
    handleSubmit,
    reset,
    control,
    formState: { errors, isSubmitting },
  } = useForm<UserInquiryFormData>({
    resolver: zodResolver(userInquirySchema),
    defaultValues: {
      full_name: "",
      contact_no: "",
      email: "",
      address: "",
      designation: "",
      department: "",
      gender: "male",
      image: ""

    },
  });

  const onSubmit = async (data: UserInquiryFormData) => {
    try {
      setMessage({ type: "success", text: "Inquiry submitted successfully!" });
      reset();
      setRefresh(!refresh);
      
    } catch (err: any) {
      setMessage({ type: "error", text: err.message || "Something went wrong" });
    }
  };


  return (
    <div className="w-full"> {/* Outer container stays full width */}
      <Form
        onSubmit={handleSubmit(onSubmit)}
        className="space-y-4 border p-6 rounded-lg bg-white w-full"
        isSubmitting={isSubmitting}
        message={message || undefined}
        submitButtonText="Submit"
        submitButtonClassName="btn-primary"
      >
        {/* Row with 2 fields */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-0">
          {/* Full Name */}
          <FormGroup>
            <Label>Full Name *</Label>
            <Input
              {...register("full_name")}
              error={!!errors.full_name}
              errorMessage={errors.full_name?.message}
              placeholder="Enter Full Name"
            />
          </FormGroup>

          {/* Contact No */}
          <FormGroup>
            <Label>Contact no *</Label>
            <Input
              {...register("contact_no")}
              error={!!errors.contact_no}
              errorMessage={errors.contact_no?.message}
              placeholder="Enter Contact no"
            />
          </FormGroup>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-0">
          {/* Email - Stays on its own row below */}
          <FormGroup>
            <Label>Email *</Label>
            <Input
              {...register("email")}
              type="email"
              error={!!errors.email}
              errorMessage={errors.email?.message}
              placeholder="Enter Email Address"
            />
          </FormGroup>

          {/* Email - Stays on its own row below */}
          <FormGroup>
            <Label>Address *</Label>
            <Input
              {...register("address")}
              type="address"
              error={!!errors.address}
              errorMessage={errors.address?.message}
              placeholder="Enter Address Address"
            />
          </FormGroup>

        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-0">

          <FormGroup>
            <Label>Designation *</Label>
            <Controller
              name="designation"
              control={control}
              render={({ field }) => (
                <Select
                  options={designationOptions}
                  placeholder="Select Designation"
                  value={field.value}
                  onChange={(val) => field.onChange(val)}
                  error={!!errors.designation}
                  errorMessage={errors.designation?.message?.toString()}
                />
              )}
            />
          </FormGroup>


          <FormGroup>
            <Label>Department *</Label>
            <Controller
              name="department"
              control={control}
              render={({ field }) => (
                <Select
                  options={departmentOptions}
                  placeholder="Select Department"
                  value={field.value}
                  onChange={(val) => field.onChange(val)}
                  error={!!errors.department}
                  errorMessage={errors.department?.message?.toString()}
                />
              )}
            />
          </FormGroup>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-0">
          <FormGroup>
            <Label>Govt Id Card *</Label>
            <Controller
              name="image"
              control={control}
              rules={{
                validate: (files) =>
                  isEdit || (files && files.length > 0)
                    ? true
                    : "Govt Id Card is required",
              }}
              render={({ field }) => (
                <FileInput
                  onChange={(e) => {
                    field.onChange(e.target.files);
                    if (e.target.files?.[0]) setImagePreview(URL.createObjectURL(e.target.files[0]));
                  }}
                  error={!!errors.image}
                  errorMessage={errors.image?.message?.toString()}
                />
              )}
            />

            {imagePreview && <img src={imagePreview} className="max-h-64 rounded-lg border mt-2" />}
          </FormGroup>

          <FormGroup>
            <Label>Gender *</Label>

            <Controller
              name="gender"
              control={control}
              render={({ field }) => (
                <div className="flex gap-6 mt-2">
                  <Radio
                    id="gender-male"
                    name="gender"
                    label="Male"
                    value="male"
                    checked={field.value === "male"}
                    onChange={(val) => field.onChange(val)}
                  />

                  <Radio
                    id="gender-female"
                    name="gender"
                    label="Female"
                    value="female"
                    checked={field.value === "female"}
                    onChange={(val) => field.onChange(val)}
                  />
                </div>
              )}
            />

            {errors.gender && (
              <p className="text-sm text-red-500 mt-1">
                {errors.gender.message}
              </p>
            )}
          </FormGroup>
        </div>
      </Form>
    </div>
  );
}