import { Control, FieldErrors, UseFormWatch, UseFormSetValue } from "react-hook-form";
import { FirstTimeHomeBuyerFormData } from "../schema";
import { incomeTypeOptions } from "../constants";
import FormInput from "@/src/components/form/FormInput";
import FormRadio from "@/src/components/form/FormRadio";
import FormSelect from "@/src/components/form/FormSelect";
import FormSection from "@/src/components/form/FormSection";

interface Step2Props {
  control: Control<FirstTimeHomeBuyerFormData>;
  errors: FieldErrors<FirstTimeHomeBuyerFormData>;
  isReadOnly: boolean;
  watch: UseFormWatch<FirstTimeHomeBuyerFormData>;
  setValue: UseFormSetValue<FirstTimeHomeBuyerFormData>;
}

export default function Step2({ control, errors, isReadOnly, watch, setValue }: Step2Props) {
  const isCurrentlyEmployed = watch("isCurrentlyEmployed");
  const coApplicantName = watch("coApplicantName");
  const applicantHasIncome = watch("applicantHasIncome");
  const coApplicantHasIncome = watch("coApplicantHasIncome");
  const applicantIncomes = watch("applicantIncomes") || [];
  const coApplicantIncomes = watch("coApplicantIncomes") || [];
  const hasCoApplicant = coApplicantName && coApplicantName.trim() !== "";

  const handleApplicantIncomeSelect = (value: string) => {
    if (!value) return;
    const exists = applicantIncomes.some((inc) => inc.incomeType === value);
    if (exists) return;

    setValue("applicantIncomes", [
      ...applicantIncomes,
      { incomeType: value, incomeAmount: "" },
    ]);
  };

  const handleApplicantIncomeAmountChange = (index: number, value: string) => {
    const updated = [...applicantIncomes];
    updated[index].incomeAmount = value;
    setValue("applicantIncomes", updated);
  };

  const removeApplicantIncome = (index: number) => {
    setValue("applicantIncomes", applicantIncomes.filter((_, i) => i !== index));
  };

  const handleCoApplicantIncomeSelect = (value: string) => {
    if (!value) return;
    const exists = coApplicantIncomes.some((inc) => inc.incomeType === value);
    if (exists) return;

    setValue("coApplicantIncomes", [
      ...coApplicantIncomes,
      { incomeType: value, incomeAmount: "" },
    ]);
  };

  const handleCoApplicantIncomeAmountChange = (index: number, value: string) => {
    const updated = [...coApplicantIncomes];
    updated[index].incomeAmount = value;
    setValue("coApplicantIncomes", updated);
  };

  const removeCoApplicantIncome = (index: number) => {
    setValue("coApplicantIncomes", coApplicantIncomes.filter((_, i) => i !== index));
  };

  return (
    <div>
      {/* Employment Status */}
      <FormSection title="Employment Status">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <FormRadio
            name="isCurrentlyEmployed"
            control={control}
            label="Are you currently employed?"
            options={[
              { label: "Yes", value: "yes" },
              { label: "No", value: "no" },
            ]}
            required
            disabled={isReadOnly}
            error={errors.isCurrentlyEmployed}
          />
        </div>
      </FormSection>

      {isCurrentlyEmployed === "yes" && (
        <>
          {/* Applicant Section */}
          <FormSection title="Applicant Information">

      <div className="p-4 border border-gray-100 rounded-lg bg-gray-50/30 space-y-4">
        <div className="grid grid-cols-12 gap-6">
          {/* Employer Name - Applicant */}
          <div className="col-span-12 md:col-span-6">
            <FormInput
              name="employerApplicant"
              control={control}
              label="Employer's Name (Applicant)"
              required
              disabled={isReadOnly}
              error={errors.employerApplicant}
            />
          </div>

          {/* Does Applicant have income */}
          <div className="col-span-12 md:col-span-6">
            <FormRadio
              name="applicantHasIncome"
              control={control}
              label="Does Applicant have income?"
              options={[
                { label: "Yes", value: "yes" },
                { label: "No", value: "no" },
              ]}
              disabled={isReadOnly}
            />
          </div>
        </div>

        {/* Income Type Selector */}
        {applicantHasIncome === "yes" && !isReadOnly && (
          <div className="col-span-12 md:col-span-6">
            <FormSelect
              name="applicantIncomeType"
              control={control}
              label="Income Type"
              options={incomeTypeOptions}
              placeholder="Select Income Type"
              onChange={(val) => handleApplicantIncomeSelect(val)}
            />
          </div>
        )}

        {/* Applicant Income Table */}
        {applicantHasIncome === "yes" && applicantIncomes.length > 0 && (
          <div className="overflow-x-auto">
            <table className="min-w-full border border-gray-200 rounded-md">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-4 py-2 text-left text-sm font-semibold">Sr No</th>
                  <th className="px-4 py-2 text-left text-sm font-semibold">Income Type</th>
                  <th className="px-4 py-2 text-left text-sm font-semibold">Income Amount</th>
                  <th className="px-4 py-2 text-left text-sm font-semibold">Action</th>
                </tr>
              </thead>
              <tbody>
                {applicantIncomes.map((income, index) => (
                  <tr key={index} className="border-t">
                    <td className="px-4 py-2 text-sm">{index + 1}</td>
                    <td className="px-4 py-2 text-sm">{income.incomeType}</td>
                    <td className="px-4 py-2">
                      <input
                        type="number"
                        value={income.incomeAmount}
                        onChange={(e) => handleApplicantIncomeAmountChange(index, e.target.value)}
                        disabled={isReadOnly}
                        className="w-full h-[45px] border rounded-md px-4 outline-none focus:ring-1 focus:ring-teal-500 border-gray-300"
                        placeholder="Enter Amount"
                      />
                    </td>
                    <td className="px-4 py-2">
                      {!isReadOnly && (
                        <button
                          type="button"
                          onClick={() => removeApplicantIncome(index)}
                          className="text-red-600 text-sm hover:underline"
                        >
                          Delete
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
        </FormSection>
      {/* Co-Applicant Section */}
      {(hasCoApplicant) && (
        <div className="mt-12 mb-8">
           <FormSection title="Co-Applicant Information">

          <div className="p-4 border border-gray-100 rounded-lg bg-gray-50/30 space-y-4">
            <div className="grid grid-cols-12 gap-6">
              {/* Employer Name - Co Applicant */}
              <div className="col-span-12 md:col-span-6">
                <FormInput
                  name="employerCoApplicant"
                  control={control}
                  label="Employer's Name (Co-Applicant)"
                  required
                  disabled={isReadOnly}
                  error={errors.employerCoApplicant}
                />
              </div>

              {/* Employer Address - Co Applicant */}
              <div className="col-span-12 md:col-span-6">
                <FormInput
                  name="employerAddressCoApplicant"
                  control={control}
                  label="Employer's Address (Co-Applicant)"
                  required
                  disabled={isReadOnly}
                  error={errors.employerAddressCoApplicant}
                />
              </div>
            </div>

            {/* Co Applicant Income Radio */}
            <div className="grid grid-cols-12 gap-6 items-end">
              <div className="col-span-12 md:col-span-6">
                <FormRadio
                  name="coApplicantHasIncome"
                  control={control}
                  label="Does Co-Applicant have income?"
                  options={[
                    { label: "Yes", value: "yes" },
                    { label: "No", value: "no" },
                  ]}
                  disabled={isReadOnly}
                />
              </div>

              {coApplicantHasIncome === "yes" && !isReadOnly && (
                <div className="col-span-12 md:col-span-6">
                  <FormSelect
                    name="coApplicantIncomeType"
                    control={control}
                    label="Income Type"
                    options={incomeTypeOptions}
                    placeholder="Select Income Type"
                    disabled={isReadOnly}
                    onChange={(val) => handleCoApplicantIncomeSelect(val)}
                  />
                </div>
              )}
            </div>

            {/* Co Applicant Income Table */}
            {coApplicantHasIncome === "yes" && coApplicantIncomes.length > 0 && (
              <div className="overflow-x-auto">
                <table className="min-w-full border border-gray-200 rounded-md">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="px-4 py-2 text-left text-sm font-semibold">Sr No</th>
                      <th className="px-4 py-2 text-left text-sm font-semibold">Income Type</th>
                      <th className="px-4 py-2 text-left text-sm font-semibold">Income Amount</th>
                      <th className="px-4 py-2 text-left text-sm font-semibold">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {coApplicantIncomes.map((income, index) => (
                      <tr key={index} className="border-t">
                        <td className="px-4 py-2 text-sm">{index + 1}</td>
                        <td className="px-4 py-2 text-sm">{income.incomeType}</td>
                        <td className="px-4 py-2">
                          <input
                            type="number"
                            value={income.incomeAmount}
                            onChange={(e) => handleCoApplicantIncomeAmountChange(index, e.target.value)}
                            disabled={isReadOnly}
                            className="w-full h-[45px] border rounded-md px-4 outline-none focus:ring-1 focus:ring-teal-500 border-gray-300"
                            placeholder="Enter Amount"
                          />
                        </td>
                        <td className="px-4 py-2">
                          {!isReadOnly && (
                            <button
                              type="button"
                              onClick={() => removeCoApplicantIncome(index)}
                              className="text-red-600 text-sm hover:underline"
                            >
                              Delete
                            </button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
          </FormSection>
        </div>
      )}
        </>
      )}
    </div>
  );
}