import { Control, useFieldArray, Controller } from "react-hook-form";
import { HomeImprovementFormData } from "../schema";
import FormInput from "@/src/components/form/FormInput";
import FormSelect from "@/src/components/form/FormSelect";
import FormRadio from "@/src/components/form/FormRadio";
import Select from "@/src/components/admin/form/Select";
import FormSection from "@/src/components/form/FormSection";

interface Step2Props {
  control: Control<HomeImprovementFormData>;
  errors: any;
  isReadOnly: boolean;
  watch: any;
}

const relationOptions = [
  { label: "Self", value: "Self" },
  { label: "Spouse", value: "Spouse" },
  { label: "Father", value: "Father" },
  { label: "Mother", value: "Mother" },
  { label: "Son", value: "Son" },
  { label: "Daughter", value: "Daughter" },
  { label: "Brother", value: "Brother" },
  { label: "Sister", value: "Sister" },
];

const incomeTypeOptions = [
  { label: "Social Security Benefits", value: "Social Security Benefits" },
  { label: "Business Income", value: "Business Income" },
  { label: "Pension", value: "Pension" },
  { label: "Salary", value: "Salary" },
];

export default function Step2({ control, errors, isReadOnly, watch }: Step2Props) {
  const { fields, append, remove, update } = useFieldArray({
    control,
    name: "householdMembers",
  });

  const watchedMembers = watch("householdMembers");

  const handleIncomeSelect = (memberIndex: number, incomeType: string) => {
    const member = watchedMembers[memberIndex];
    const newIncome = { incomeType, incomeAmount: "" };
    const updatedIncomes = [...(member.incomes || []), newIncome];
    update(memberIndex, { ...member, incomes: updatedIncomes });
  };

  const handleIncomeAmountChange = (memberIndex: number, incomeIndex: number, amount: string) => {
    const member = watchedMembers[memberIndex];
    const updatedIncomes = member.incomes.map((income: any, idx: number) =>
      idx === incomeIndex ? { ...income, incomeAmount: amount } : income
    );
    update(memberIndex, { ...member, incomes: updatedIncomes });
  };

  const removeIncomeRow = (memberIndex: number, incomeIndex: number) => {
    const member = watchedMembers[memberIndex];
    const updatedIncomes = member.incomes.filter((_: any, idx: number) => idx !== incomeIndex);
    update(memberIndex, { ...member, incomes: updatedIncomes });
  };
   
  return (
    <div className="space-y-8">
      <FormSection title="Household Information">
        <div className="space-y-6">
          {fields.map((field, index) => (
            <div key={field.id} className="p-4 border rounded-lg bg-gray-50">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <FormInput
                  name={`householdMembers.${index}.name`}
                  control={control}
                  label="Name of Household Member"
                  placeholder="Name"
                  disabled={isReadOnly}
                  error={errors.householdMembers?.[index]?.name}
                />



                <FormSelect
                  name={`householdMembers.${index}.relationWithApplicant`}
                  control={control}
                  label="Relation with Applicant"
                  options={relationOptions}
                  placeholder="Select Relation"
                  disabled={isReadOnly}
                  error={errors.householdMembers?.[index]?.relationWithApplicant}
                />

                <FormInput
                  name={`householdMembers.${index}.age`}
                  control={control}
                  label="Age"
                  type="number"
                  placeholder="Age"
                  disabled={isReadOnly}
                  error={errors.householdMembers?.[index]?.age}
                />

                <FormRadio
                  name={`householdMembers.${index}.hasIncome`}
                  control={control}
                  label="Does this member have income?"
                  options={[
                    { label: "Yes", value: "yes" },
                    { label: "No", value: "no" },
                  ]}
                  disabled={isReadOnly}
                  error={errors.householdMembers?.[index]?.hasIncome}
                />
              </div>

              {watchedMembers[index]?.hasIncome === "yes" && (
                <div className="mt-4 space-y-4">
                  {!isReadOnly && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <label className="text-sm font-medium text-gray-700 mb-1 block">
                          Income Type
                        </label>
                        <Select
                          options={incomeTypeOptions.map(opt => ({ ...opt, value: opt.value }))}
                          placeholder="Select Income Type"
                          value={""}
                          onChange={(val) => handleIncomeSelect(index, String(val))}
                          disabled={isReadOnly}
                        />
                      </div>
                    </div>
                  )}

                  {watchedMembers[index]?.incomes?.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>
                          {watchedMembers[index]?.incomes?.map((income: any, incomeIndex: number) => (
                            <tr key={incomeIndex} className="border-t">
                              <td className="px-4 py-2 text-sm">{incomeIndex + 1}</td>
                              <td className="px-4 py-2 text-sm">{income.incomeType}</td>
                              <td className="px-4 py-2">
                                <Controller
                                  name={`householdMembers.${index}.incomes.${incomeIndex}.incomeAmount`}
                                  control={control}
                                  render={({ field }) => (
                                    <input
                                      type="number"
                                      value={field.value}
                                      onChange={field.onChange}
                                      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={() => removeIncomeRow(index, incomeIndex)}
                                    className="text-red-600 text-sm hover:underline"
                                  >
                                    Delete
                                  </button>
                                )}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>
              )}

              {!isReadOnly && fields.length > 1 && (
                <button
                  type="button"
                  onClick={() => remove(index)}
                  className="mt-4 text-red-500 text-sm hover:underline"
                >
                  Remove Member
                </button>
              )}
            </div>
          ))}

          {!isReadOnly && (
            <button
              type="button"
              onClick={() => append({ name: "", age: "0", hasIncome: "no", relationWithApplicant: "", incomes: [] })}
              className="px-4 py-2 text-sm font-semibold text-teal-600 border border-teal-500 rounded-md hover:bg-teal-50"
            >
              + Add Additional Household Member
            </button>
          )}
        </div>
      </FormSection>

      <div>
        <FormSection title="Income Summary">

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormInput
              name="grossAnnualIncome"
              control={control}
              label="Gross Annual Household Income"
              type="number"
              placeholder="Enter gross annual income"
              required
              disabled={isReadOnly}
              error={errors.grossAnnualIncome}
            />


          </div>
        </FormSection>
      </div>
      <div>
        <FormSection title="Household Counts">

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">


            <FormInput
              name="totalPersons"
              control={control}
              label="Total Persons in Dwelling"
              type="number"
              placeholder="Total persons"
              required
              disabled={isReadOnly}
              error={errors.totalPersons}
            />

            <FormInput
              name="childrenUnder18"
              control={control}
              label="Number of Children Under 18"
              type="number"
              placeholder="Number of children"
              required
              disabled={isReadOnly}
              error={errors.childrenUnder18}
            />
          </div>
        </FormSection>
      </div>
    </div>
  );
}
