import React, { useEffect } from "react";
import { useForm, useFieldArray, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import TagInput from "../common/TagInput";
import { z } from "zod";

export const directorySchema = z.object({
  firstName: z.string().min(1, "First Name is required"),
  lastName: z.string().min(1, "Last Name is required"),
  organization: z.string().min(1, "Organization name is required"),
  type: z.string().min(1, "Type is required"),
  address: z.string().optional(),
  description: z.string().min(1, { message: "Description is required" }),
  email: z
    .array(z.string().email("Invalid email"))
    .nonempty("At least one email required"),
  phone: z
    .array(z.string().regex(/^\d{10}$/, "Phone must be 10 digits"))
    .nonempty("At least one phone number is required"),
  tags: z.array(z.string()).optional(),
});



const ManageDirectory = () => {
  const methods = useForm({
    resolver: zodResolver(directorySchema),
    defaultValues: {
      firstName: "",
      lastName: "",
      organization: "",
      type: "",
      address: "",
      description: "",
      email: [""],
      phone: [""],
      tags: [],
    },
  });

  const {
    register,
    handleSubmit,
    control,
    getValues,
    trigger,
    formState: { errors },
  } = methods;

  const {
    fields: emailFields,
    append: appendEmail,
    remove: removeEmail,
  } = useFieldArray({ control, name: "email" });

  const {
    fields: phoneFields,
    append: appendPhone,
    remove: removePhone,
  } = useFieldArray({ control, name: "phone" });

  useEffect(() => {
    if (emailFields.length === 0) appendEmail(""); 
    if (phoneFields.length === 0) appendPhone(""); 
  }, [emailFields.length, phoneFields.length]);

  const onSubmit = (data) => {
    // console.log("Submitted:\n" + JSON.stringify(data, null, 2));
  };

  const handleAddEmail = async () => {
    const emails = getValues("email");
    const lastIndex = emails.length - 1;
    const valid = await trigger(`email.${lastIndex}`);
    if (valid) appendEmail(""); 
  };

  const handleAddPhone = async () => {
    const phones = getValues("phone");
    const lastIndex = phones.length - 1;
    const valid = await trigger(`phone.${lastIndex}`);
    if (valid) appendPhone(""); 
  };

  return (
    <FormProvider {...methods}>
      <form className="p-2 p-sm-0" onSubmit={handleSubmit(onSubmit)}>
        <div className="row">
          <div className="col-md-6">
            <label className="form-label">First Name</label>
            <input className="form-control form-control-sm" {...register("firstName")} />
            {errors.firstName && <small className="danger-text">{errors.firstName.message}</small>}
          </div>

          <div className="col-md-6">
            <label className="form-label">Last Name</label>
            <input className="form-control form-control-sm" {...register("lastName")} />
            {errors.lastName && <small className="danger-text">{errors.lastName.message}</small>}
          </div>
        </div>

        <div className="col-12">
          <label className="form-label">Organization</label>
          <input className="form-control form-control-sm" {...register("organization")} />
          {errors.organization && <small className="danger-text">{errors.organization.message}</small>}
        </div>

        <div className="row">
          <div className="col-md-6">
            <label className="form-label">Email</label>
            {emailFields.map((field, index) => (<>
              <div key={field.id} className="d-flex align-items-center mb-1">
                <input
                  type="email"
                  className="form-control form-control-sm"
                  {...register(`email.${index}`)}
                  placeholder="email@example.com"
                />
                {index === emailFields.length - 1 ? (
                  <button
                    type="button"
                    className="btn btn-xs btn-primary ms-1"
                    onClick={handleAddEmail}
                  >
                    <i className="bx bx-plus bx-xs" />
                  </button>
                ) : (
                  <button
                    type="button"
                    className="btn btn-xs btn-danger ms-1"
                    onClick={() => removeEmail(index)} 
                  >
                    <i className="bx bx-x bx-xs" />
                  </button>
                )}
              </div>
              {errors.email?.[index] && (
        <small className="danger-text ms-2">
          {errors.email[index]?.message}
        </small>
      )}
              </>
            ))}
                  

          </div>

          <div className="col-md-6">
            <label className="form-label">Phone</label>
            {phoneFields.map((field, index) => (<>
              <div key={field.id} className="d-flex align-items-center mb-1">
                <input
                  type="text"
                  className="form-control form-control-sm"
                  {...register(`phone.${index}`)}
                  placeholder="9876543210"
                />
                {index === phoneFields.length - 1 ? (
                  <button
                    type="button"
                    className="btn btn-xs btn-primary ms-1"
                    onClick={handleAddPhone}
                  >
                    <i className="bx bx-plus bx-xs" />
                  </button>
                ) : (
                  <button
                    type="button"
                    className="btn btn-xs btn-danger ms-1"
                    onClick={() => removePhone(index)} // Remove the phone field
                  >
                    <i className="bx bx-x bx-xs" />
                  </button>
                )}
              </div>
              {errors.phone?.[ index ] && <small className="danger-text ms-2">{errors.phone[ index ]?.message}</small>}
              </>
            ))}
         
          </div>
        </div>

        <div className="row my-1">
          <div className="col-md-6">
            <label className="form-label">Type</label>
            <input className="form-control form-control-sm" {...register("type")} />
            {errors.type && <small className="danger-text">{errors.type.message}</small>}
          </div>
          <div className="col-md-6">
            <TagInput name="tags" label="Tags" />
          </div>
        </div>

        <div className="col-12">
          <label className="form-label">Address</label>
          <textarea className="form-control form-control-sm" rows="2" {...register("address")} />
        </div>

        <div className="col-12">
          <label className="form-label">Description</label>
          <textarea className="form-control form-control-sm" rows="2" {...register("description")} />
          {errors.description && <small className="danger-text">{errors.description.message}</small>}
        </div>

        <div className="d-flex justify-content-evenly py-2">
          <button className="btn btn-sm btn-primary" type="submit">Submit</button>
          <button className="btn btn-sm btn-secondary" type="button">Cancel</button>
        </div>
      </form>
    </FormProvider>
  );
};

export default ManageDirectory;
