import { Formik } from "formik";
import React from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import * as yup from "yup";

import { Banner, BottomButton } from "../../components/common";

import CommonStyles from "../../constants/CommonStyles";
import Colors from "../../constants/colors";

interface IncidentReportFormProps {
  incidentReportPagedata: any;
  submitIncident: (values: any) => void;
  navigation: any;
}

const radioButtonOptions = [
  { label: "Yes", value: "yes" },
  { label: "No", value: "no" },
];

export const IncidentReportForm: React.FC<IncidentReportFormProps> = ({
  incidentReportPagedata,
  submitIncident,
  navigation,
}) => {
  if (!incidentReportPagedata?.incidentReportDashboardForm) {
    alert("Network Error");
    return null;
  }

  const {
    incidentReportDashboardForm: {
      entities,
      incident_types,
      incident_sub_types,
      incident_groups,
      areas,
      people_role_types,
      user_emails,
      contractor_emails,
      nationalities,
    },
  } = incidentReportPagedata;

  const contractorRoleTypeId =
    people_role_types.find((type: any) => type.name === "Contractor")?.id ?? "";
  const staffRoleTypeId =
    people_role_types.find((type: any) => type.name === "Staff")?.id ?? "";

  const incidentReportFormSchema = yup.object().shape({
    title: yup.string().required("Title is required"),
    incidentGroup: yup.array().min(1, "Incident Group is required"),
    incidentType: yup.array().min(1, "Incident Type is required"),
    incidentSubType: yup.array(),
    group: yup.array().min(1, "Location is required"),
    date: yup.date().required("Date is required"),
    time: yup.date().required("Time is required"),
    area: yup.array().min(1, "Area is required"),
    involvedPeople: yup.array().of(
      yup.object().shape({
        involvedUserRole: yup.array(),
        user: yup.array(),
        involvedPersonName: yup.string().when("involvedUserRole", ([involvedUserRole], schema) => {
          if (!involvedUserRole?.length) return schema.nullable();
          if (involvedUserRole[0] === contractorRoleTypeId || involvedUserRole[0] === staffRoleTypeId) {
            return schema.nullable();
          }
          return schema.required("Involved Person Name is required");
        }),
        phoneNumber: yup.string(),
        Nationality: yup.array(),
        address: yup.string(),
      })
    ),
    witnesses: yup.array().of(
      yup.object().shape({
        involvedUserRole: yup.array(),
        user: yup.array(),
        involvedPersonName: yup.string().when("involvedUserRole", ([involvedUserRole], schema) => {
          if (!involvedUserRole?.length) return schema.nullable();
          if (involvedUserRole[0] === contractorRoleTypeId || involvedUserRole[0] === staffRoleTypeId) {
            return schema.nullable();
          }
          return schema.required("Witness name is required");
        }),
        phoneNumber: yup.string(),
        Nationality: yup.array(),
        address: yup.string(),
      })
    ),
    body: yup.string().required("Description is required"),
    field_firstaid: yup.string().nullable(),
    field_staff_off_from_work: yup.string().nullable(),
    field_staff_off_days: yup
      .string()
      .when("field_staff_off_from_work", ([field_staff_off_from_work], schema) => {
        if (field_staff_off_from_work === "yes") {
          return schema
            .required("Staff off days required")
            .test("isNumber", "Please provide valid number", (value) =>
              !isNaN(Number(value))
            );
        }
        return schema.nullable();
      }),
    field_taken_home: yup.string().nullable(),
    field_hospitalized: yup.string().nullable(),
    field_no_of_days_hospitalized: yup
      .string()
      .when("field_hospitalized", ([field_hospitalized], schema) => {
        if (field_hospitalized === "yes") {
          return schema
            .required("Hospitalization days required")
            .test("isNumber", "Please provide valid number", (value) =>
              !isNaN(Number(value))
            );
        }
        return schema.nullable();
      }),
    field_sent_or_taken_to_hospital: yup.string().nullable(),
    field_hospital_name: yup.string().when("field_sent_or_taken_to_hospital", ([field_sent_or_taken_to_hospital], schema) => {
      if (field_sent_or_taken_to_hospital === "yes") {
        return schema.required("Hospital name is required");
      }
      return schema.nullable();
    }),
  });

  return (
    <Formik
      key="incidentReportForm"
      validateOnChange={false}
      validateOnBlur={true}
      initialValues={{
        title: "",
        incidentType: [],
        incidentSubType: [],
        group: [],
        incidentGroup: [],
        date: "",
        time: "",
        area: [],
        involvedPeople: [
          {
            involvedUserRole: [],
            user: [],
            involvedPersonName: "",
            phoneNumber: "",
            Nationality: [],
            address: "",
          },
        ],
        witnesses: [
          {
            involvedPersonName: "",
            phoneNumber: "",
            involvedUserRole: [],
            user: [],
            address: "",
            Nationality: [],
          },
        ],
        body: "",
        field_firstaid: "",
        field_staff_off_from_work: "",
        field_staff_off_days: "",
        field_taken_home: "",
        field_hospitalized: "",
        field_no_of_days_hospitalized: "",
        field_sent_or_taken_to_hospital: "",
        field_hospital_name: "",
        images: [],
        videos: [],
        docs: [],
      }}
      validationSchema={incidentReportFormSchema}
      onSubmit={(values) => {
        submitIncident(values);
        navigation.navigate("Home");
      }}
    >
      {({ handleChange, handleBlur, handleSubmit, values, setFieldValue, errors, touched, isSubmitting }) => (
        <View style={CommonStyles.screen}>
          <ScrollView>
            <View style={{ padding: 15 }}>
              <Banner title="Incident Reporting" image={require("../../assets/images/incidents.png")} />

              {/* Example field */}
              <Text style={[CommonStyles.subTitle, { marginTop: 30 }]}>Incident Title</Text>
              <TextInput
                placeholder="Incident Title"
                placeholderTextColor={Colors.colorPlaceholder}
                onChangeText={handleChange("title")}
                onBlur={handleBlur("title")}
                value={values.title}
                style={[CommonStyles.textInput, { marginTop: 2 }]}
              />
              {errors.title && <Text style={CommonStyles.errorTextStyle}>{errors.title}</Text>}

              {/* Add all other Field components like FormikSelect, FormikDatePicker, etc. */}
              {/* ... */}
            </View>
          </ScrollView>

          <BottomButton
            isSubmitting={isSubmitting}
            buttonText="Submit"
            pressCallBack={handleSubmit}
          />
        </View>
      )}
    </Formik>
  );
};

const styles = StyleSheet.create({
  fieldArrayContainer: {
    borderColor: Colors.colorTextField,
    borderRadius: 5,
    backgroundColor: Colors.colorTextField,
    borderWidth: 1,
    padding: 15,
  },
  addButton: {
    borderColor: Colors.buttonColor,
    alignSelf: "flex-end",
    width: "25%",
    justifyContent: "center",
    right: 20,
    marginTop: 10,
    borderRadius: 5,
    backgroundColor: Colors.buttonColor,
  },
});