import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
import { HomeImprovementFormData } from "../schema";
import FormInput from "@/src/components/form/FormInput";
import SignatureBox from "@/src/components/admin/SignatureBox";

interface Step5Props {
  control: Control<HomeImprovementFormData>;
  errors: any;
  isReadOnly: boolean;
  setValue: UseFormSetValue<HomeImprovementFormData>;
}

export default function Step5({ control, errors, isReadOnly, setValue }: Step5Props) {
  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>

      {/* 1 - Certification */}
      <div className="border border-gray-200 rounded-xl p-6 bg-gray-50 mt-10">
        <h3 className="text-md font-medium text-center mb-8">
          Home Improvement Program – Required Certifications
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
          {/* Applicant */}
          <div className="border border-gray-200 rounded-xl p-6 bg-white">
            <Controller
              name="certificationSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  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">
              <div>
                <FormInput
                  name="certificationSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.certificationSignerName}
                />
              </div>
              <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>

          {/* Co-Applicant */}
          <div className="border border-gray-200 rounded-xl p-6 bg-white">
            <Controller
              name="certificationCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={errors.certificationCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("certificationCoApplicantDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="certificationCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  disabled={isReadOnly}
                  error={errors.certificationCoApplicantSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="certificationCoApplicantDateTime"
                  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>

      {/* 2 - Authorization to Receive & Verify Employment Information */}
      <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 */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="employmentAuthSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  value={field.value || ""}
                  error={errors.employmentAuthSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("employmentAuthDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="employmentAuthSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.employmentAuthSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="employmentAuthDateTime"
                  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 */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="employmentAuthCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={errors.employmentAuthCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("employmentAuthCoApplicantDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="employmentAuthCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  disabled={isReadOnly}
                  error={errors.employmentAuthCoApplicantSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="employmentAuthCoApplicantDateTime"
                  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>

      {/* 3 - Authorization of 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 */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="inspectionAuthSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  value={field.value || ""}
                  error={errors.inspectionAuthSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("inspectionAuthDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="inspectionAuthSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.inspectionAuthSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="inspectionAuthDateTime"
                  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 */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="inspectionAuthCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={errors.inspectionAuthCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("inspectionAuthCoApplicantDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="inspectionAuthCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  disabled={isReadOnly}
                  error={errors.inspectionAuthCoApplicantSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="inspectionAuthCoApplicantDateTime"
                  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>

      {/* 4 - 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
        </h3>

        <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
          <Controller
            name="bidResponsibilitySignature"
            control={control}
            render={({ field }) => (
              <SignatureBox
                title="Applicant Signature"
                value={field.value || ""}
                error={errors.bidResponsibilitySignature?.message}
                readOnly={isReadOnly}
                onChange={(val) => {
                  field.onChange(val);
                  if (val && !field.value) {
                    setValue("bidResponsibilityDateTime", 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="bidResponsibilitySignerName"
                control={control}
                label="Legal Name of Signer"
                placeholder="Enter full legal name"
                required
                disabled={isReadOnly}
                error={errors.bidResponsibilitySignerName}
              />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">
                Date & Time of Signature
              </label>
              <Controller
                name="bidResponsibilityDateTime"
                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>

      {/* 5 - Subordination of AHC Notes & Mortgages */}
      <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">
          Subordination of AHC Notes &amp; Mortgages
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
          {/* Applicant */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="subordinationSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Applicant Signature"
                  value={field.value || ""}
                  error={errors.subordinationSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("subordinationDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="subordinationSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  required
                  disabled={isReadOnly}
                  error={errors.subordinationSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="subordinationDateTime"
                  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 (NEWLY ADDED) */}
          <div className="border border-gray-200 rounded-xl p-6 bg-gray-50">
            <Controller
              name="subordinationCoApplicantSignature"
              control={control}
              render={({ field }) => (
                <SignatureBox
                  title="Co-Applicant Signature"
                  value={field.value || ""}
                  error={(errors as any).subordinationCoApplicantSignature?.message}
                  readOnly={isReadOnly}
                  onChange={(val) => {
                    field.onChange(val);
                    if (val && !field.value) {
                      setValue("subordinationCoApplicantDateTime", new Date().toISOString());
                    }
                  }}
                />
              )}
            />

            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <FormInput
                  name="subordinationCoApplicantSignerName"
                  control={control}
                  label="Legal Name of Signer"
                  placeholder="Enter full legal name"
                  disabled={isReadOnly}
                  error={errors.subordinationCoApplicantSignerName}
                />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Date & Time of Signature
                </label>
                <Controller
                  name="subordinationCoApplicantDateTime"
                  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>
  );
}