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

// Assuming these are your custom/internal components.
// Their props are inferred from usage in the original code.
import Colors from '../../constants/colors';
import CommonStyles from '../../constants/CommonStyles';
import { Banner, BottomButton } from '../common';
import { FormikDatePicker, FormikSelect } from '../formikComponents';

// --- Type Definitions ---

// A generic type for options used in select components
interface Option {
  id: string | number;
  name: string;
}

// Defines the shape of the form's values
interface PermitFormValues {
  title: string;
  field_start_date: Date | null;
  field_end_date: Date | null;
  field_job_location: (string | number)[]; // Assuming the value is an array of IDs
  field_invited_contractor: (string | number)[];
  field_job_details: string;
  webform: (string | number)[];
}

// Defines the props passed to the PermitForm component
interface PermitFormProps {
  submitPermit: (values: PermitFormValues) => void;
  // Assuming the data props are arrays of Option objects
  field_job_location: Option[];
  webform: Option[]; // This might need a more complex structure if it's location-dependent
  field_invited_contractor: Option[];
  navigation: {
    navigate: (screen: string) => void;
  };
}

// --- Validation Schema ---

const PermitFormSchema = yup.object().shape({
  title: yup.string().required('Project Name is required'),
  field_start_date: yup.date().required("Start Date is required").nullable(),
  field_end_date: yup
    .date()
    .required("End Date is required")
    .nullable()
    .min(yup.ref('field_start_date'), "End date can't be before start date"),
  field_job_location: yup.array().min(1, "Job Location is required").required("Job Location is required"),
  field_invited_contractor: yup.array().min(1, "Invited Contractor is required").required("Invited Contractor is required"),
  field_job_details: yup.string().required('Job Details is required'),
  webform: yup.array().min(1, "Permit Form is required").required("Permit Form is required"),
});


// --- Component ---

export const PermitForm: React.FC<PermitFormProps> = ({
  submitPermit,
  field_job_location,
  webform,
  field_invited_contractor,
  navigation
}) => {

  const initialValues: PermitFormValues = {
    title: '',
    field_start_date: null,
    field_end_date: null,
    field_job_location: [],
    field_invited_contractor: [],
    field_job_details: '',
    webform: [],
  };

  // NOTE: This assumes webform and contractor options are NOT dependent on job location.
  // If they ARE dependent, the logic in the commented-out block of the original
  // code should be implemented using a useEffect hook.

  const handleSubmitForm = (values: PermitFormValues, { setSubmitting }: FormikHelpers<PermitFormValues>) => {
    submitPermit(values);
    navigation.navigate('Home');
    // Consider adding a toast message here using a modern library like 'react-native-toast-message'
    setSubmitting(false);
  };

  return (
    <Formik
      key="PermitForm"
      validateOnChange={true}
      validateOnBlur={true}
      initialValues={initialValues}
      onSubmit={handleSubmitForm}
      validationSchema={PermitFormSchema}
    >
      {({ handleChange, handleBlur, handleSubmit, values, setFieldValue, errors, touched, isSubmitting }) => (
        <>
          <ScrollView>
            <View style={styles.container}>
              <Banner title={'Contractors & \nSuppliers Management'} image={require('../../assets/images/permit.png')} />
              <Text style={CommonStyles.subTitle}>Enter Details</Text>

              {/* Project Name */}
              <TextInput
                placeholder="Project Name"
                onChangeText={handleChange('title')}
                placeholderTextColor={Colors.colorPlaceholder}
                onBlur={handleBlur('title')}
                value={values.title}
                style={CommonStyles.textInput}
              />
              {touched.title && errors.title && <Text style={CommonStyles.errorTextStyle}>{errors.title}</Text>}

              {/* Job Location Select */}
              <Field
                name="field_job_location"
                component={FormikSelect}
                setFieldValue={setFieldValue}
                isSelectSingle={true}
                title='Job Location'
                popupTitle="Select Job Location"
                data={field_job_location || []}
              />
              {touched.field_job_location && errors.field_job_location && <Text style={CommonStyles.errorTextStyle}>{errors.field_job_location}</Text>}

              {/* Permit Form Select */}
              <Field
                name="webform"
                component={FormikSelect}
                setFieldValue={setFieldValue}
                isSelectSingle={true}
                title='Permit Form'
                popupTitle="Select Permit WebForm"
                data={webform || []}
              />
              {touched.webform && errors.webform && <Text style={CommonStyles.errorTextStyle}>{errors.webform}</Text>}

              {/* Invited Contractor Select */}
              <Field
                name="field_invited_contractor"
                component={FormikSelect}
                setFieldValue={setFieldValue}
                isSelectSingle={false} // Allows multiple selections
                title='Invited Contractor'
                popupTitle="Select Invited Contractor"
                data={field_invited_contractor || []}
              />
              {touched.field_invited_contractor && errors.field_invited_contractor && <Text style={CommonStyles.errorTextStyle}>{errors.field_invited_contractor}</Text>}

              {/* Start Date */}
              <Field
                name="field_start_date"
                component={FormikDatePicker}
                setFieldValue={setFieldValue}
                placeholder="Select Start Date.."
                minDate={new Date()}
              />
              {touched.field_start_date && errors.field_start_date && <Text style={CommonStyles.errorTextStyle}>{errors.field_start_date}</Text>}

              {/* End Date */}
              <Field
                name="field_end_date"
                component={FormikDatePicker}
                setFieldValue={setFieldValue}
                placeholder="Select End Date.."
                minDate={values.field_start_date || new Date()} // End date cannot be before start date
              />
              {touched.field_end_date && errors.field_end_date && <Text style={CommonStyles.errorTextStyle}>{errors.field_end_date}</Text>}

              {/* Job Details Textarea */}
              <TextInput
                multiline
                numberOfLines={5}
                placeholderTextColor={Colors.colorPlaceholder}
                placeholder="Job Details"
                onChangeText={handleChange('field_job_details')}
                onBlur={handleBlur('field_job_details')}
                value={values.field_job_details}
                style={[CommonStyles.item, styles.textArea]}
              />
              {touched.field_job_details && errors.field_job_details && <Text style={CommonStyles.errorTextStyle}>{errors.field_job_details}</Text>}

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15
  },
  textArea: {
    height: 100, // Give a fixed height to the multiline input
    textAlignVertical: 'top', // Crucial for Android
    marginTop: 8,
    borderWidth: Platform.OS === 'ios' ? 1 : 0.5, // Native-base 'bordered' style
    borderColor: '#ddd',
    padding: 10,
  }
});