import {
  Control,
  FieldErrors,
  Controller,
  UseFormSetValue,
  useWatch,
} from "react-hook-form";
import { FirstTimeHomeBuyerFormData } from "../schema";
import FormInput from "@/src/components/form/FormInput";
import SignatureBox from "@/src/components/admin/SignatureBox";

interface Step4Props {
  control: Control<FirstTimeHomeBuyerFormData>;
  errors: FieldErrors<FirstTimeHomeBuyerFormData>;
  isReadOnly: boolean;
  setValue: UseFormSetValue<FirstTimeHomeBuyerFormData>;
}

export default function Step4({
  control,
  errors,
  isReadOnly,
  setValue,
}: Step4Props) {
  const formatDateTime = (iso: string | undefined) => {
    return iso ? new Date(iso).toLocaleString() : "—";
  };

  const notaryDay = useWatch({ control, name: "notaryDay" }) as string;
  const notaryMonth = useWatch({ control, name: "notaryMonth" }) as string;
  const notaryYear = useWatch({ control, name: "notaryYear" }) as string;
  const notaryAppearedName = useWatch({ control, name: "notaryAppearedName" }) as string;

  return (
    <div>
      <h2 className="text-lg font-semibold mb-8 text-center">
        Certifications & Authorizations
      </h2>

      {/* TWO SIGNATURES GRID */}

      {/* LEFT - Certification */}
      <div className="border border-gray-200 rounded-xl p-6 bg-gray-50 mt-10">
        <Controller
          name="certificationSignature"
          control={control}
          render={({ field }) => (
            <SignatureBox
              title="Home Improvement Program – Required Certification"
              value={field.value || ""}
              error={errors.certificationSignature?.message}
              readOnly={isReadOnly}
              onChange={(val) => {
                field.onChange(val);
                if (val && !field.value) {
                  setValue("certificationDateTime", new Date().toISOString());
                }
              }}
            />
          )}
        />

        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
          {/* Legal Signer Name */}
          <div>
            <FormInput
              name="certificationSignerName"
              control={control}
              label="Legal Name of Signer"
              placeholder="Enter full legal name"
              required
              disabled={isReadOnly}
              error={errors.certificationSignerName}
            />
          </div>

          {/* Date & Time */}
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">
              Date & Time of Signature
            </label>
            <Controller
              name="certificationDateTime"
              control={control}
              render={({ field }) => (
                <input
                  type="text"
                  readOnly
                  value={formatDateTime(field.value || "")}
                  className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed"
                />
              )}
            />
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl p-6 md:p-8 mt-10 border border-gray-200">
        <h3 className="text-md font-medium text-center mb-8">
          Authorization to Receive & Verify Employment Information
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
          {/* APPLICANT SECTION */}

          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="authorizationSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  value={field.value || ""}
                  error={errors.authorizationSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue(
                        "authorizationDateTime",
                        new Date().toISOString(),
                      );
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              {/* Legal Signer Name */}
              <div>
                <FormInput
                  name="authorizationSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.authorizationSignerName}
                />
              </div>

              {/* Date & Time */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="authorizationDateTime"
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed"
                    />
                  )}
                />
              </div>
            </div>
          </div>

          {/* CO-APPLICANT SECTION */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="authorizationCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={errors.authorizationCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue(
                        "authorizationCoApplicantDateTime",
                        new Date().toISOString(),
                      );
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              {/* Legal Signer Name */}
              <div>
                <FormInput
                  name="authorizationCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  // required
                  disabled={isReadOnly}
                  error={errors.authorizationCoApplicantSignerName}
                />
              </div>

              {/* Date & Time */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="authorizationCoApplicantDateTime"
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed"
                    />
                  )}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* INSPECTION */}

      <div className="bg-white rounded-xl p-6 md:p-8 mt-10 border border-gray-200">
        <h3 className="text-md font-medium text-center mb-8">
          AUTHORIZATION OF INSPECTION
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
          {/* APPLICANT SECTION */}

          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="inspectionSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Signer Name "
                  value={field.value || ""}
                  error={errors.inspectionSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("inspectionDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              {/* Legal Signer Name */}
              <div>
                <FormInput
                  name="inspectionSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.inspectionSignerName}
                />
              </div>

              {/* Date & Time */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time
                </label>
                <Controller
                  name="inspectionDateTime"
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed font-mono text-sm"
                    />
                  )}
                />
              </div>
            </div>
          </div>

          {/* CO-APPLICANT INSPECTION SECTION */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="inspectionCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={
                    (errors as any).inspectionCoApplicantSignature?.message
                  }
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue(
                        "inspectionCoApplicantDateTime" as any,
                        new Date().toISOString(),
                      );
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              <div>
                <FormInput
                  name="inspectionCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  // required
                  disabled={isReadOnly}
                  error={(errors as any).inspectionCoApplicantSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time
                </label>
                <Controller
                  name={"inspectionCoApplicantDateTime" as any}
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed font-mono text-sm"
                    />
                  )}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* BID RESPONSIBILITY */}
      <div className="bg-white rounded-xl p-6 md:p-8 mt-10 border border-gray-200">
        <h3 className="text-md font-medium text-center mb-8">
          BID RESPONSIBILITY / Subordination of AHC Notes & Mortgages
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
          {/* APPLICANT SECTION */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="bidApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  value={field.value || ""}
                  error={errors.bidApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue(
                        "bidApplicantDateTime",
                        new Date().toISOString(),
                      );
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              {/* Legal Signer Name */}
              <div>
                <FormInput
                  name="bidApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.bidApplicantSignerName}
                />
              </div>

              {/* Date & Time */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="bidApplicantDateTime"
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed"
                    />
                  )}
                />
              </div>
            </div>
          </div>

          {/* CO-APPLICANT SECTION */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="bidCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={errors.bidCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue(
                        "bidCoApplicantDateTime",
                        new Date().toISOString(),
                      );
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl mx-auto">
              {/* Legal Signer Name */}
              <div>
                <FormInput
                  name="bidCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  // required
                  disabled={isReadOnly}
                  error={errors.bidCoApplicantSignerName}
                />
              </div>

              {/* Date & Time */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="bidCoApplicantDateTime"
                  control={control}
                  render={({ field }) => (
                    <input
                      type="text"
                      readOnly
                      value={formatDateTime(field.value || "")}
                      className="w-full h-[45px] border rounded-md px-4 py-2 bg-gray-100 cursor-not-allowed"
                    />
                  )}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* NOTARY PUBLIC ACKNOWLEDGEMENT SECTION */}
      <div className="mt-10 border border-gray-200 bg-gray-50 rounded-xl p-6">
        <h4 className="text-sm font-semibold uppercase tracking-wider text-teal-900 mb-4 pb-2 border-b border-gray-200">
          Notary Public Acknowledgement
        </h4>

        {/* Legal Statement Text */}
        <p className="text-sm text-gray-600 leading-relaxed mb-6 bg-white p-4 rounded-lg border border-gray-100 ">
          On the{" "}
          <span className="font-semibold text-teal-700 text-base">
            {notaryDay || "______"}
          </span>{" "}
          day of{" "}
          <span className="font-semibold text-teal-700 text-base">
            {notaryMonth || "______"}
          </span>
          , in the year{" "}
          <span className="font-semibold text-teal-700 text-base">
            {notaryYear || "_______"}
          </span>
          , before me, the undersigned, a notary public in and for said state,
          personally appeared{" "}
          <span className="font-semibold text-teal-700 text-base">
            {notaryAppearedName || "_______________________________"}
          </span>
          , personally known to me or proved to me on the basis of satisfactory
          evidence to be the individual(s) whose name(s) is/are subscribed to
          the within instrument and acknowledged to me that he/she/they executed
          the same in his/her/their capacity(ies), and that by his/her/their
          signature(s) on the instrument, the individual(s), or the person upon
          behalf of which the individual(s) acted, executed the instrument.
        </p>

        {/* Notary Input Fields Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
          <FormInput
            name="notaryDay"
            control={control}
            label="Day"
            placeholder="e.g. 18"
            required
            disabled={isReadOnly}
            error={errors.notaryDay}
          />
          <FormInput
            name="notaryMonth"
            control={control}
            label="Month"
            placeholder="e.g. May"
            required
            disabled={isReadOnly}
            error={errors.notaryMonth}
          />
          <FormInput
            name="notaryYear"
            control={control}
            label="Year"
            placeholder="e.g. 2026"
            required
            disabled={isReadOnly}
            error={errors.notaryYear}
          />
          <FormInput
            name="notaryAppearedName"
            control={control}
            label="Name of Individual(s) Appeared"
            placeholder="Enter full legal name(s)"
            required
            disabled={isReadOnly}
            error={errors.notaryAppearedName}
            className="sm:col-span-2 md:col-span-1"
          />
        </div>
      </div>
    </div>
  );
}
