import React, { useState, useEffect, forwardRef, useCallback } from 'react';
import { View, TouchableOpacity } from 'react-native';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { MyTextInput, MyText, Checkbox, ImageUploaderNeo, tw, useFocusCallback, BottomDropdown, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';

interface StoreOption {
  id: number;
  name: string;
}

interface TagFormData {
  tagName: string;
  tagDescription: string;
  isDashboardTag: boolean;
  relatedStores: number[];
}

interface TagFormProps {
  mode: 'create' | 'edit';
  initialValues: TagFormData;
  existingImageUrl?: string;
  onSubmit: (values: TagFormData, images: ImageUploaderNeoItem[], removedExisting: boolean) => void;
  isLoading: boolean;
  stores?: StoreOption[];
}

const TagForm = forwardRef<any, TagFormProps>(({
  mode,
  initialValues,
  existingImageUrl: existingImageUrlRaw,
  onSubmit,
  isLoading,
  stores: storesRaw,
}, ref) => {
  const [images, setImages] = useState<ImageUploaderNeoItem[]>([])
  const [removedExisting, setRemovedExisting] = useState(false)
  const [isDashboardTagChecked, setIsDashboardTagChecked] = useState<boolean>(Boolean(initialValues.isDashboardTag));

  const existingImageUrl = existingImageUrlRaw || ''
  const stores = storesRaw || []

  // Update checkbox when initial values change
  useEffect(() => {
    setIsDashboardTagChecked(Boolean(initialValues.isDashboardTag));
    if (existingImageUrl) {
      setImages([{ imgUrl: existingImageUrl, mimeType: null }])
    } else {
      setImages([])
    }
    setRemovedExisting(false)
  }, [existingImageUrlRaw, initialValues.isDashboardTag]);
  

  const validationSchema = Yup.object().shape({
    tagName: Yup.string()
      .required('Tag name is required')
      .min(1, 'Tag name must be at least 1 character')
      .max(100, 'Tag name must be less than 100 characters'),
    tagDescription: Yup.string()
      .max(500, 'Description must be less than 500 characters'),
  });

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={(values) => onSubmit(values, images, removedExisting)}
      enableReinitialize
    >
      {({ handleChange, handleSubmit, values, setFieldValue, errors, touched, setFieldValue: formikSetFieldValue, resetForm }) => {
        // Clear form when screen comes into focus
          const clearForm = useCallback(() => {
            setImages([])
            setRemovedExisting(false)
            setIsDashboardTagChecked(false);
            resetForm();
          }, [resetForm]);

        useFocusCallback(clearForm);

        return (
          <View style={tw`p-4`}>
            <MyTextInput
              topLabel="Tag Name"
              placeholder="Enter tag name"
              value={values.tagName}
              onChangeText={handleChange('tagName')}
              style={{ marginBottom: 16 }}
            />

            <MyTextInput
              topLabel="Description (Optional)"
              placeholder="Enter tag description"
              multiline
              numberOfLines={3}
              value={values.tagDescription}
              onChangeText={handleChange('tagDescription')}
              style={{ marginBottom: 16 }}
            />

            {/* Image Upload Section */}
            <View style={tw`mb-6`}>
              <MyText style={tw`text-lg font-bold mb-2 text-gray-800`}>
                Tag Image {mode === 'edit' ? '(Upload new to replace)' : '(Optional)'}
              </MyText>


              <ImageUploaderNeo
                images={images}
                onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
                  setImages((prev) => [...prev, ...payload.map((img) => ({
                    imgUrl: img.url,
                    mimeType: img.mimeType,
                  }))])
                }}
                onImageRemove={(payload) => {
                  if (payload.mimeType === null) {
                    setRemovedExisting(true)
                  }
                  setImages((prev) => prev.filter((item) => item.imgUrl !== payload.url))
                }}
                allowMultiple={false}
              />
            </View>

            {/* Dashboard Tag Checkbox */}
            <View style={tw`flex-row items-center mb-6`}>
              <Checkbox
                checked={isDashboardTagChecked}
                onPress={() => {
                  const newValue = !isDashboardTagChecked;
                  setIsDashboardTagChecked(newValue);
                  formikSetFieldValue('isDashboardTag', newValue);
                }}
              />
              <MyText style={tw`ml-3 text-gray-800`}>Mark as Dashboard Tag</MyText>
            </View>

            {/* Related Stores Dropdown */}
            <View style={tw`mb-6`}>
              <MyText style={tw`text-lg font-bold mb-2 text-gray-800`}>
                Related Stores
              </MyText>
              <BottomDropdown
                label="Select Related Stores"
                placeholder="Select stores..."
                value={values.relatedStores.map(id => id.toString())}
                options={stores.map(store => ({
                  label: store.name,
                  value: store.id.toString(),
                }))}
                onValueChange={(selectedValues) => {
                  const numericValues = (selectedValues as string[]).map(v => parseInt(v));
                  formikSetFieldValue('relatedStores', numericValues);
                }}
                multiple={true}
              />
            </View>

            <TouchableOpacity
              onPress={() => handleSubmit()}
              disabled={isLoading}
              style={tw`px-4 py-3 rounded-lg shadow-lg items-center ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
            >
              <MyText style={tw`text-white text-lg font-bold`}>
                {isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Tag' : 'Update Tag')}
              </MyText>
            </TouchableOpacity>
          </View>
        );
      }}
    </Formik>
  );
});

TagForm.displayName = 'TagForm';

export default TagForm;
