import { NativeStackScreenProps } from "@react-navigation/native-stack";
import React, { useCallback, useEffect, useState } from "react";
import {
    Dimensions,
    KeyboardAvoidingView,
    Platform,
    StatusBar,
    StyleSheet,
    Text,
    View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useDispatch, useSelector } from "react-redux";
import { FilterComponent } from "../../components/common";
import { QuestionsForm } from "../../components/forms/QuestionsForm";
import Colors from "../constants/Colors";
import { submitAudit } from "../store/actions/auditFormScreenActions";
import {
    draftAnswer,
    removeSubmittedFormDraft,
} from "../store/actions/qustionActions";
import { RootState } from "../store/store"; // ✅ adjust to your store type
import { getNaAnswerData } from "../utils/questionUtils";

const { width } = Dimensions.get("window");

const zero_1_2 = [
  { value: "0", color: Colors.color_00, label: "00" },
  { value: "1", color: Colors.color_01, label: "01" },
  { value: "2", color: Colors.color_02, label: "02" },
  { value: "na", color: Colors.color_NA, label: "NA" },
];

const yes_no_na = [
  { value: "yes", color: Colors.color_02, label: "Y" },
  { value: "no", color: Colors.color_00, label: "N" },
  { value: "na", color: Colors.color_NA, label: "NA" },
];

type RootStackParamList = {
  AuditForm: {
    auditFormId: string;
    selectedEntity: string;
    auditTypeId: string;
    selectedGroup: string[];
    selectedBUManager: string;
  };
};

type Props = NativeStackScreenProps<RootStackParamList, "AuditForm">;

const AuditFormScreen: React.FC<Props> = ({ route, navigation }) => {
  const dispatch = useDispatch();

  const { auditFormId, selectedEntity, auditTypeId, selectedGroup, selectedBUManager } =
    route.params;

  const { auditFormData, userInfo, draftAnswerData, incidentReport } =
    useSelector((state: RootState) => ({
      auditFormData: state.auditFormData,
      userInfo: state.userInfo,
      draftAnswerData: state.draftAnswerData,
      incidentReport: state.incidentReport,
    }));

  const [state, setState] = useState({
    photo: [] as string[],
    selectedGroup: "",
    isActionplan: false,
    filter: "ViewAll",
    showFilters: false,
    progress: 0,
  });

  const auditForm = auditFormData.data.audit_forms[auditFormId] || {};
  const audits = auditFormData.data.audit_types[selectedEntity] || [];

  // ✅ set dynamic header
  useEffect(() => {
    const formName =
      audits.find((item: any) => item.form_id === auditFormId)?.form || "";

    if (Platform.OS === "ios") {
      navigation.setOptions({
        headerTitle: () => (
          <SafeAreaView style={{ flex: 1, paddingLeft: 8, marginRight: 8 }}>
            <Text numberOfLines={2} ellipsizeMode="tail" style={{ textAlign: "center", paddingLeft: 8 }}>
              {formName.toUpperCase()}
            </Text>
          </SafeAreaView>
        ),
      });
    } else {
      navigation.setOptions({
        headerBackground: () => (
          <View
            style={{
              flex: 1,
              marginLeft: 20,
              marginRight: 20,
              justifyContent: "center",
              width: width - 30,
            }}
          >
            <Text numberOfLines={2} ellipsizeMode="tail" style={{ textAlign: "center", paddingLeft: 8 }}>
              {formName.toUpperCase()}
            </Text>
          </View>
        ),
        title: "",
      });
    }
  }, [auditFormId, audits, navigation]);

  const getRadioOptions = (radio_type: string) =>
    radio_type === "0_1_2" ? zero_1_2 : yes_no_na;

  const calculateProgress = useCallback((percentage: number) => {
    setState((prev) => ({ ...prev, progress: Number((percentage / 100).toFixed(2)) }));
  }, []);

  const submitAuditCall = (data: any) => {
    const token = userInfo?.userInfo?.access_token ?? "";
    const naAnswer = getNaAnswerData(auditForm, selectedGroup);
    dispatch(
      submitAudit(
        { ...data, ...naAnswer },
        auditFormId,
        selectedEntity,
        auditTypeId,
        token,
        selectedBUManager
      )
    );
  };

  const draftAnswers = (draftValues: any, formId: string, score: number) => {
    dispatch(
      draftAnswer(
        draftValues,
        formId,
        "Audit",
        selectedEntity,
        selectedGroup,
        "",
        score,
        selectedBUManager
      )
    );
  };

  const removeSubmittedFormDrafts = (formId: string) => {
    dispatch(removeSubmittedFormDraft(formId, selectedEntity));
  };

  const groupListData = getGroupListData(auditForm, selectedGroup);
  let questions = formatQuestions(auditForm, [], selectedGroup);

  if (state.selectedGroup) {
    questions = filterQuestions(questions, groupListData, state.selectedGroup);
  }

  const radioButtonOptions = getRadioOptions(auditForm.radio_type);

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      {...(Platform.OS === "ios" ? { keyboardVerticalOffset: 88, behavior: "padding" } : {})}
    >
      <View style={{ flex: 1 }}>
        <StatusBar backgroundColor={Colors.statusBarColor} barStyle="light-content" />
        <FilterComponent
          isActionplan={state.isActionplan}
          groupData={groupListData}
          selectedGroup={state.selectedGroup}
          filter={state.filter}
          setFilter={(value) => setState((prev) => ({ ...prev, filter: value }))}
          actionPlanToggle={() => setState((prev) => ({ ...prev, isActionplan: !prev.isActionplan }))}
          setGroup={(value) => setState((prev) => ({ ...prev, selectedGroup: value }))}
          progress={state.progress}
        />
        <View style={styles.questionsForm}>
          <QuestionsForm
            selectedGroup={state.selectedGroup}
            userEmails={incidentReport.incidentReportDashboardForm.user_emails}
            isActionplan={state.isActionplan}
            draftAnswer={draftAnswers}
            removeSubmittedFormDraft={removeSubmittedFormDrafts}
            draftAnswerData={draftAnswerData}
            type="Audit"
            formId={auditFormId}
            isUnAnswered={state.filter === "unanswered"}
            data={questions}
            clearFilter={() => setState((prev) => ({ ...prev, selectedGroup: "", filter: "unanswered" }))}
            submitAnswer={submitAuditCall}
            radioButtonOptions={radioButtonOptions}
            navigation={navigation}
            selectedEntity={selectedEntity}
            triggerActionPlanFilter={() => setState((prev) => ({ ...prev, isActionplan: true }))}
            calculateProgress={calculateProgress}
          />
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};

// ✅ helper fns with TS
const formatQuestions = (auditForm: any, questions: any[], selectedGroup: string[]) => {
  if (!auditForm) return [];
  Object.entries(auditForm.groups || {}).forEach(([key, value]: [string, any]) => {
    if (selectedGroup.includes(key)) {
      const newQuestions = value.questions.map((q: any) => ({
        ...q,
        group_title: value.group_title,
      }));
      questions = [...questions, ...newQuestions];
    }
  });
  return questions;
};

const getGroupListData = (auditForm: any, selectedGroup: string[]) => {
  const result: { title: string; key: string }[] = [];
  if (!auditForm) return result;
  Object.entries(auditForm.groups || {}).forEach(([key, value]: [string, any]) => {
    if (selectedGroup.includes(key)) {
      result.push({ title: value.group_title, key });
    }
  });
  return result;
};

const filterQuestions = (questions: any[], groupListData: any[], selectedGroup: string) => {
  const groupTitle = groupListData.find((item) => item.key === selectedGroup)?.title ?? "";
  return questions.filter((q) => q.group_title === groupTitle);
};

const styles = StyleSheet.create({
  questionsForm: {
    backgroundColor: "#FFF",
    flexGrow: 1,
  },
});

export default AuditFormScreen;
