import React, { useEffect, useState } from 'react';
import Label from '../common/Label';
import { useFormContext, useForm, FormProvider } from 'react-hook-form';
import { useIndustries, useTenantDetails, useUpdateTenantDetails } from '../../hooks/useTenant';
import { orgSize, reference } from '../../utils/constants';
import { LogoUpload } from './LogoUpload';
import showToast from '../../services/toastService';
import { zodResolver } from '@hookform/resolvers/zod';
import { EditTenant } from './TenantSchema';

const EditProfile = ({ TenantId, onClose }) => {
  const { data, isLoading, isError, error } = useTenantDetails(TenantId);
  const [logoPreview, setLogoPreview] = useState(null);
  const [logoName, setLogoName] = useState("");
  const { data: Industries, isLoading: industryLoading, isError: industryError } = useIndustries();
  const { mutate: UpdateTenant, isPending, } = useUpdateTenantDetails(() => {
    showToast("Tenant Details Updated Successfully", "success")
    onClose()

  })
  const methods = useForm({
    resolver: zodResolver(EditTenant),
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      contactNumber: "",
      description: "",
      domainName: "",
      billingAddress: "",
      taxId: "",
      logoImage: "",
      officeNumber: "",
      organizationSize: "",
      industryId: "",
      reference: "",
    }
  });

  const { register, reset, handleSubmit, formState: { errors } } = methods;

  const onSubmit = (formData) => {
    const tenantPayload = { ...formData, contactName: `${formData.firstName} ${formData.lastName}`, id: data.id, }
    UpdateTenant({ id: data.id, tenantPayload })
  };

  useEffect(() => {
    if (data && Industries) {
      const [first = "", last = ""] = (data.contactName ?? "").split(" ");
      reset({
        firstName: first,
        lastName: last,
        contactNumber: data.contactNumber ?? "",
        description: data.description ?? "",
        domainName: data.domainName ?? "",
        billingAddress: data.billingAddress ?? "",
        taxId: data.taxId ?? "",
        logoImage: data.logoImage ?? "",
        officeNumber: data.officeNumber ?? "",
        organizationSize: data.organizationSize ?? "",
        industryId: data.industry?.id ?? "",
        reference: data.reference ?? "",
      });
      setLogoPreview(data.logoImage)
    }
  }, [data, Industries, reset]);

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>{error?.message}</div>;


  return (
    <FormProvider {...methods}>
      <form className="row g-6" onSubmit={handleSubmit(onSubmit)}>
        <h6>Edit Tenant</h6>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="firstName" required>First Name</Label>
          <input id="firstName" type="text" className="form-control form-control-sm" {...register("firstName")} inputMode='text' />
          {errors.firstName && <div className="danger-text">{errors.firstName.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="lastName" required>Last Name</Label>
          <input id="lastName" type="text" className="form-control form-control-sm" {...register("lastName")} />
          {errors.lastName && <div className="danger-text">{errors.lastName.message}</div>}
        </div>



        <div className="col-sm-6 mt-1">
          <Label htmlFor="contactNumber" required>Contact Number</Label>
          <input id="contactNumber" type="text" className="form-control form-control-sm" {...register("contactNumber")} inputMode="tel"
            placeholder="+91 9876543210" />
          {errors.contactNumber && <div className="danger-text">{errors.contactNumber.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="domainName" >Domain Name</Label>
          <input id="domainName" type="text" className="form-control form-control-sm" {...register("domainName")} />
          {errors.domainName && <div className="danger-text">{errors.domainName.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="taxId" >Tax ID</Label>
          <input id="taxId" type="text" className="form-control form-control-sm" {...register("taxId")} />
          {errors.taxId && <div className="danger-text">{errors.taxId.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="officeNumber" >Office Number</Label>
          <input id="officeNumber" type="text" className="form-control form-control-sm" {...register("officeNumber")} />
          {errors.officeNumber && <div className="danger-text">{errors.officeNumber.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="industryId" required>Industry</Label>
          <select className="form-select form-select-sm" {...register("industryId")}>
            {industryLoading ? <option value="">Loading...</option> :
              Industries?.map((indu) => (
                <option key={indu.id} value={indu.id}>{indu.name}</option>
              ))
            }
          </select>
          {errors.industryId && <div className="danger-text">{errors.industryId.message}</div>}
        </div>

        <div className="col-sm-6 mt-1">
          <Label htmlFor="reference">Reference</Label>
          <select className="form-select form-select-sm" {...register("reference")}>
            {reference.map((org) => (
              <option key={org.val} value={org.val}>{org.name}</option>
            ))}
          </select>
          {errors.reference && <div className="danger-text">{errors.reference.message}</div>}
        </div>
        <div className="col-sm-6">
          <Label htmlFor="organizationSize" required>
            Organization Size
          </Label>

          <select
            className="form-select form-select-sm"
            {...register("organizationSize")}
          >
            {orgSize.map((org) => (
              <option key={org.val} value={org.val}>
                {org.name}
              </option>
            ))}
          </select>
          {errors.organizationSize && (
            <div className="danger-text">{errors.organizationSize.message}</div>
          )}
        </div>

        <div className="col-12 mt-1">
          <Label htmlFor="billingAddress" required>Billing Address</Label>
          <textarea id="billingAddress" className="form-control" {...register("billingAddress")} rows={2} />
          {errors.billingAddress && <div className="danger-text">{errors.billingAddress.message}</div>}
        </div>

        <div className="col-12 mt-1">
          <Label htmlFor="description">Description</Label>
          <textarea id="description" className="form-control" {...register("description")} rows={2} />
          {errors.description && <div className="danger-text">{errors.description.message}</div>}
        </div>

        <div className="col-sm-12">
          <Label htmlFor="logImage">Logo Image</Label>
          <LogoUpload
            preview={logoPreview}
            setPreview={setLogoPreview}
            fileName={logoName}
            setFileName={setLogoName}
          />
        </div>

        <div className="d-flex justify-content-center gap-2 mt-3">
          <button type="submit" disabled={isPending} className="btn btn-sm btn-primary">{isPending ? "Please Wait..." : "Submit"}</button>
          <button type="button" disabled={isPending} className="btn btn-sm btn-secondary" onClick={onClose}>Cancel</button>
        </div>
      </form>
    </FormProvider>
  );
};

export default EditProfile;
