<template>
  <div class="lg:flex items-start justify-center mt-4">
    <FormSheet class="mx-2 mb-4 lg:w-3/4">
      <ClientOnly>
        <Vueform
          v-if="!formSubmitted"
          ref="form$"
          validate-on="change"
          :form-data="(form$) => form$.requestData"
          @response="handleResponse"
          endpoint="farmer"
        >
          <div class="text-xl mb-1 col-span-12">
            <div class="border-b border-gray-300 pb-2">
              Farmer onboarding survey
            </div>
          </div>
          <TextElement
            name="phone"
            label="What is your primary phone number?"
            description="Enter a valid Kenyan phone number starting with 07 or 01 that you registered with."
            rules="required|phone"
          />
          <div class="text mb-1 mt-1 col-span-12">
            <div class="border-b border-gray-300 pb-2">Farm Details</div>
          </div>
          <GroupElement name="farm_details">
            <SelectElement
              name="county"
              label="What county are you located in?"
              :native="false"
              :items="{
                kirinyaga: 'Kirinyaga',
                muranga: 'Muranga',
                nakuru: 'Nakuru',
                meru: 'Meru',
                uasin_gishu: 'Uasin Gishu',
                kajiado: 'Kajiado',
              }"
              rules="required"
            />
            <TextElement
              name="sub_county"
              label="What sub-county are you located in?"
              rules="required|max:50"
            />
            <TextElement
              name="farming_area_acres"
              input-type="number"
              label="How many acres of land are you currently farming?"
              rules="required|min:1|numeric"
            />
            <TagsElement
              name="planned_crops"
              label="Which crops do you plan to grow in the coming season?"
              :items="{
                rice: 'Rice',
                coffee: 'Coffee',
                tea: 'Tea',
                sugarcane: 'Sugarcane',
                miraa: 'Miraa',
                avocados: 'Avocados',
                maize: 'Maize',
                potatoes: 'Potatoes',
                sorghum: 'Sorghum',
                other_fruits: 'Other fruits',
                other_vegetables: 'Other vegetables',
                other_grains: 'Other grains',
              }"
              rules="required"
              description="Select all options that apply."
            />
          </GroupElement>
          <div class="text mt-4 col-span-12">
            <div class="border-b border-gray-300 pb-2">
              Past Harvest Details
            </div>
          </div>
          <div class="col-span-12">
            <Notice
              subtitle="Select all the crops that you have planted in the last 3 years, the average harvest you have gotten (in kg/acre) and how much you have earned (in ksh/kg) on selling each crop."
            />
          </div>
          <ListElement
            name="past_harvest_details"
            label="Harvest details for the last 3 years"
            :min="1"
          >
            <template #default="{ index }">
              <p>Crop {{ index + 1 }}</p>
              <ObjectElement :name="index">
                <SelectElement
                  name="crop_type"
                  rules="required"
                  :search="true"
                  :items="{
                    rice: 'Rice',
                    coffee: 'Coffee',
                    tea: 'Tea',
                    sugarcane: 'Sugarcane',
                    miraa: 'Miraa',
                    avocados: 'Avocados',
                    maize: 'Maize',
                    potatoes: 'Potatoes',
                    sorghum: 'Sorghum',
                    other_fruits: 'Other fruits',
                    other_vegetables: 'Other vegetables',
                    other_grains: 'Other grains',
                  }"
                />
                <TextElement
                  name="average_harvest"
                  label="Average harvest"
                  description="Average yield/output in kg/acre."
                  rules="required|min:1|numeric"
                />
                <TextElement
                  name="average_earning"
                  label="Average earning"
                  description="Average yield/output in ksh/kg."
                  rules="required|min:1|numeric"
                />
                <div class="col-span-12">
                  <div class="border-t border-gray-300 mt-1"></div>
                </div>
              </ObjectElement>
            </template>
          </ListElement>
          <div class="text mt-4 col-span-12">
            <div class="border-b border-gray-300 pb-2">
              Budget and Expenditure Details
            </div>
          </div>
          <TextElement
            name="total_expenditure"
            input-type="number"
            label="On average, how much do you spend on seeds, fertilizers, and crop protection (herbicides, pesticides, etc.) for a year?"
            description="Average in ksh. per year"
            rules="required|min:1|numeric"
          />
          <GroupElement name="expenditure_details">
            <StaticElement
              name="static"
              description="Total percentage should add upto 100%"
              >How would you say your budget is split between seeds,
              fertilizers, and crop protection?</StaticElement
            >
            <TextElement
              columns="4"
              name="seeds_expenditure_percentage"
              input-type="number"
              label="Seeds %"
              rules="required|min:0|numeric|max:100"
            />
            <TextElement
              columns="4"
              name="fertilizer_expenditure_percentage"
              input-type="number"
              label="Fertilizer %"
              rules="required|min:0|numeric|max:100"
              F
            />
            <TextElement
              columns="4"
              name="crops_protection_expenditure_percentage"
              input-type="number"
              label="Crops Protection %"
              rules="required|min:0|numeric|max:100"
            />
          </GroupElement>
          <GroupElement name="fertilizer_expenditure_details">
            <StaticElement
              name="static"
              description="Total percentage should add upto 100%"
              >How is your spend on fertilizers split between
              synthetic/inorganic fertilizers (like DAP, NPK, etc.) and
              organic/natural fertilizers (like manure, compost,
              etc.)</StaticElement
            >
            <TextElement
              columns="6"
              name="synthetic_fertilizers_expenditure_percentage"
              input-type="number"
              label="Synthetic Fertilizers %"
              rules="required|min:0|numeric|max:100"
            />
            <TextElement
              columns="6"
              name="natural_fertilizers_expenditure_percentage"
              input-type="number"
              label="Natural Fertilizers %"
              rules="required|min:0|numeric|max:100"
            />
          </GroupElement>

          <StaticElement
            name="static"
            description="You can add upto 3 expenses."
            >Which input—seeds, fertilizers, or crop protection—has increased
            the most in cost for you over the past 3 years?</StaticElement
          >
          <ListElement name="increased_expenses" :min="0">
            <template #default="{ index }">
              <p>Expense</p>
              <ObjectElement :name="index">
                <SelectElement
                  rules="required"
                  name="expense_type"
                  :native="false"
                  :items="{
                    fertilizers: 'Fertilizers',
                    seeds: 'Seeds',
                    crop_protection: 'Crop Protection',
                  }"
                />
                <TagsElement
                  rules="required"
                  name="increased_expense_actions"
                  label="How have you dealt with the cost increase?"
                  :items="{
                    no_change: 'No Change',
                    cheap_alternative: 'Purchased and used cheaper alternative',
                    less_quantity: 'Purchased and used less quantity',
                    more_quantity: 'Purchased more',
                    other: 'Other',
                  }"
                  description="Select all options that apply."
                />
                <SelectElement
                  name="expense_action_overall_effect"
                  label="Have these changes affected how much you harvest?"
                  :native="false"
                  rules="required"
                  :items="{
                    increased_yields: 'Increased yields',
                    no_change_yields: 'No change to yields',
                    decreased_yields: 'Decreased yields',
                    other: 'Other',
                  }"
                />
                <div class="col-span-12">
                  <div class="border-t border-gray-300 mt-1"></div>
                </div>
              </ObjectElement>
            </template>
          </ListElement>
          <div class="text mt-4 col-span-12">
            <div class="border-b border-gray-300 pb-2">EverGrow</div>
          </div>
          <SelectElement
            name="evergrow_past"
            :native="false"
            label="Have you used EverGrow before?"
            rules="required"
            :items="{
              yes: 'Yes',
              no: 'No',
            }"
          />
          <TextElement
            name="evergrow_first"
            label="What year did you first begin using EverGrow?"
            :conditions="[['evergrow_past', 'yes']]"
            input-type="number"
            rules="required|min:2018|numeric"
          />
          <TextElement
            name="evergrow_application"
            label="What is your typical application rate of EverGrow?"
            description="Average in kg/acre."
            :conditions="[['evergrow_past', 'yes']]"
            input-type="number"
            rules="required|min:1|numeric"
          />
          <TagsElement
            name="evergrow_crops"
            label="What crops have you seen the most success with using EverGrow?"
            :items="{
              rice: 'Rice',
              coffee: 'Coffee',
              tea: 'Tea',
              sugarcane: 'Sugarcane',
              miraa: 'Miraa',
              avocados: 'Avocados',
              maize: 'Maize',
              potatoes: 'Potatoes',
              sorghum: 'Sorghum',
              other_fruits: 'Other fruits',
              other_vegetables: 'Other vegetables',
              other_grains: 'Other grains',
            }"
            :conditions="[['evergrow_past', 'yes']]"
            description="Select all options that apply."
            rules="required"
          />
          <TextElement
            columns="12"
            name="evergrow_yield"
            input-type="number"
            label="How much have your yields typically improved by when using EverGrow (vs. when not)?"
            description="Enter a percentage value"
            :conditions="[['evergrow_past', 'yes']]"
            rules="required|min:0|max:100|numeric"
          />
          <div class="text mt-4 col-span-12">
            <div class="border-b border-gray-300 pb-2">Other Fertilizers</div>
          </div>
          <SelectElement
            label="Do you use any other types of fertilizer on your land?"
            name="other_fertilizers"
            :native="false"
            :items="{
              yes: 'Yes',
              no: 'No',
              not_sure: 'Not Sure',
            }"
            rules="required"
          />
          <StaticElement
            :conditions="[['other_fertilizers', 'yes']]"
            name="static"
            description="You can add upto 3 other fertilizer types."
            >Select all other fertilizer types that you have used in the
            past?</StaticElement
          >
          <ListElement
            name="other_fertilizers_details"
            :conditions="[['other_fertilizers', 'yes']]"
            rules="required"
          >
            <template #default="{ index }">
              <p>Fertilizer</p>
              <ObjectElement :name="index">
                <SelectElement
                  rules="required"
                  name="other_fertilizer_type"
                  :native="false"
                  :items="{
                    synthetic: 'Synthetic Fertilizer',
                    commercial_organic: 'Commercial Organic Fertilizer',
                    self_made: 'Self-made fertilizer/manure',
                  }"
                />
                <TextElement
                  name="other_fertilizer_application"
                  input-type="number"
                  label="What is your typical application rate of this type of fertilizer?"
                  description="Average in kg/acre."
                  rules="required|min:1|numeric"
                />
                <TagsElement
                  rules="required"
                  name="other_fertilizer_crops"
                  label="What crops have you seen the most success with using this type of fertilizer"
                  :items="{
                    rice: 'Rice',
                    coffee: 'Coffee',
                    tea: 'Tea',
                    sugarcane: 'Sugarcane',
                    miraa: 'Miraa',
                    avocados: 'Avocados',
                    maize: 'Maize',
                    potatoes: 'Potatoes',
                    sorghum: 'Sorghum',
                    other_fruits: 'Other fruits',
                    other_vegetables: 'Other vegetables',
                    other_grains: 'Other grains',
                  }"
                  description="Select all options that apply."
                />
                <div class="col-span-12">
                  <div class="border-t border-gray-300 mt-1"></div>
                </div>
              </ObjectElement>
            </template>
          </ListElement>
          <div class="text mt-4 col-span-12">
            <div class="border-b border-gray-300 pb-2">
              Fertilizer Purchase Details
            </div>
          </div>
          <div class="col-span-12">
            <Notice
              subtitle="This applies for all types of fertilizers you purchase including Evergrow. "
            />
          </div>
          <TagsElement
            name="purchase_channels"
            rules="required"
            label="Where do you typically purchase your fertilizer from?"
            :items="{
              manufacturers: 'Direct from manufacturers',
              distributors: 'Distributors',
              resellers: 'Resellers',
              farmers: 'Fellow farmers',
              other: 'Other',
            }"
            description="Select all options that apply."
          />
          <ButtonElement name="submit" add-class="mt-2" submits>
            Submit
          </ButtonElement>
        </Vueform>
        <SuccessAlert
          v-else
          title="Submission Successful"
          subtitle="Thank you for submitting the form."
          link="/"
          action="Home"
        />
      </ClientOnly>
    </FormSheet>
  </div>
</template>

<script setup>
const form$ = ref(null);
const formSubmitted = ref(false);

const handleResponse = async (response, form$) => {
  if (response.status <= 201) {
    formSubmitted.value = true;
  } else {
    form$.messageBag.append(response.data?.error);
    if (Object.keys(response.data.data)[0]?.message) {
      form$.messageBag.append(
        Object.keys(response.data.data)[0] +
          ": " +
          Object.values(response.data.data)[0]?.message
      );
    }
  }
};
</script>
