import { Toast } from "@/components/common";
import { surveys } from '@/services/survey';
import { COLOR_SCALES } from '@/theme/colors';
import { FLEX } from "@/theme/mixins";
import { paragraph, title } from '@/theme/typography';
import { Ionicons } from '@expo/vector-icons';
import { router, useLocalSearchParams } from "expo-router";
import * as SecureStore from "expo-secure-store";
import React, { useEffect, useState } from "react";
import { ActivityIndicator, StatusBar, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import SurveyProgress from "./components/SurveyProgress";
import SurveyQuestion from "./components/SurveyQuestion";
import SurveyReport from "./components/SurveyReport";

export default function SurveyScreen() {
  const params = useLocalSearchParams();
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState([]);
  const [showReport, setShowReport] = useState(false);
  const [survey, setSurvey] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastType, setToastType] = useState("error");
  const [currentAnswer, setCurrentAnswer] = useState(null);

  const fetchSurvey = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await surveys();
      if (response?.success && response?.data?.surveys?.[0]) {
        setSurvey(response.data.surveys[0]);
      } else {
        setError('Anket bulunamadı');
      }
    } catch (err) {
      setError('Anket yüklenirken bir hata oluştu');
      console.error('Anket yükleme hatası:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchSurvey();
  }, []);

  const handleSelectAnswer = (answer) => {
    const qType = survey?.Questions?.[currentQuestionIndex]?.type;
    if (qType === "multiple") {
      setCurrentAnswer((prev) => {
        const prevArray = Array.isArray(prev) ? prev : [];
        return prevArray.includes(answer)
          ? prevArray.filter((v) => v !== answer)
          : [...prevArray, answer];
      });
    } else {
      setCurrentAnswer(answer);
    }
  };

  const handleContinue = () => {
    if (currentAnswer) {
      // Mevcut cevabı kaydet
      setAnswers(prev => [...prev, {
        questionId: survey.Questions[currentQuestionIndex].id,
        answer: currentAnswer
      }]);

      // Sonraki soruya geç
      if (currentQuestionIndex < survey.Questions.length - 1) {
        setCurrentQuestionIndex(prev => prev + 1);
        setCurrentAnswer(null);
      }
    }
  };

  const handleSurveyComplete = () => {
    setToastMessage('Anketiniz başarıyla gönderildi');
    setToastType('success');
    setShowToast(true);
    // Survey tamamlandı flag'i set et — layout tekrar yönlendirmesin
    SecureStore.setItemAsync('surveyCompleted', 'true').catch(() => {});
    setTimeout(() => {
      router.replace("/(tabs)/home");
    }, 1500);
  };

  const handleSurveyError = (errorMessage) => {
    setToastMessage(errorMessage || 'Anket gönderilirken bir hata oluştu');
    setToastType('error');
    setShowToast(true);
    setTimeout(() => {
      router.replace("/(tabs)/home");
    }, 2000);
  };

  const handleBack = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex((prevIndex) => prevIndex - 1);
    } else {
      router.push("/(auth)/login");
    }
  };

  const handleAcceptReport = async () => {
    // TODO: Anketi tamamla ve ana sayfaya yönlendir
    setShowReport(false);
    router.replace("/(tabs)");
  };

  const handleRejectReport = () => {
    setShowReport(false);
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={COLOR_SCALES.primary[50]} />
      </View>
    );
  }

  if (error || !survey?.Questions?.length) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>
          {error || 'Anket bulunamadı'}
        </Text>
      </View>
    );
  }

  const currentQuestion = survey.Questions[currentQuestionIndex];
  const isLastQuestion = currentQuestionIndex === survey.Questions.length - 1;

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />

      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={handleBack}
        >
          <Ionicons name="arrow-back" size={24} color="#000" />
        </TouchableOpacity>
        <Text style={styles.title}>{survey.title}</Text>
        <Text style={styles.progress}>
          {currentQuestionIndex + 1}/{survey.Questions.length}
        </Text>
      </View>

      <SurveyProgress
        currentStep={currentQuestionIndex + 1}
        totalSteps={survey.Questions.length}
      />

      {showReport ? (
        <SurveyReport
          onAccept={handleAcceptReport}
          onReject={handleRejectReport}
        />
      ) : (
        <SurveyQuestion
          question={currentQuestion}
          selectedAnswer={currentAnswer}
          onSelectAnswer={handleSelectAnswer}
          onContinue={handleContinue}
          isAnswerSelected={
            currentQuestion?.type === "multiple"
              ? Array.isArray(currentAnswer) && currentAnswer.length > 0
              : !!currentAnswer
          }
          isLastQuestion={isLastQuestion}
          allAnswers={answers}
          onSurveyComplete={handleSurveyComplete}
          onSurveyError={handleSurveyError}
          surveyId={survey.id}
        />
      )}

      <Toast
        visible={showToast}
        message={toastMessage}
        type={toastType}
        onHide={() => setShowToast(false)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#fff",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  errorText: {
    ...paragraph['M/Regular'],
    color: COLOR_SCALES.helper.red,
    textAlign: 'center',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingTop: 60,
    paddingBottom: 20,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#F2F2F7',
  },
  backButton: {
    padding: 8,
  },
  title: {
    ...title['M/Bold'],
    color: "#000",
    flex: 1,
    textAlign: 'center',
    marginHorizontal: 16,
  },
  progress: {
    ...paragraph['S/Medium'],
    color: "#000",
  },
});
