import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Alert,
  ActivityIndicator,
} from "react-native";
import { useUser, useAuth } from "@clerk/clerk-expo";
import { useRouter } from "expo-router";
import { fitnessProfileApi } from "@/api/fitnessProfile";

export default function OnboardingScreen() {
  const { user } = useUser();
  const { getToken } = useAuth();
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [gyms, setGyms] = useState<
    Array<{ id: string; name: string; location?: string }>
  >([]);
  const [gymsLoading, setGymsLoading] = useState<boolean>(false);
  const [selectedGymId, setSelectedGymId] = useState<string | null>(null);

  useEffect(() => {
    const loadGyms = async () => {
      try {
        setGymsLoading(true);
        const token = await getToken();
        const res = await fetch("/api/gyms", {
          headers: token ? { Authorization: `Bearer ${token}` } : undefined,
        });
        const data = await res.json();
        if (Array.isArray(data)) {
          setGyms(data);
        }
      } catch (e) {
        console.error("Failed to fetch gyms:", e);
      } finally {
        setGymsLoading(false);
      }
    };
    loadGyms();
  }, []);
  const [fitnessProfile, setFitnessProfile] = useState({
    height: "",
    weight: "",
    goals: "",
    fitnessLevel: "beginner",
    medicalConditions: "",
    dietaryRestrictions: "",
    preferredWorkoutTime: "morning",
    workoutFrequency: "3",
  });

  const handleSubmit = async () => {
    if (!user?.id) return;

    try {
      setIsSubmitting(true);

      // Validate required fields
      if (!fitnessProfile.height || !fitnessProfile.weight) {
        Alert.alert("Error", "Please enter your height and weight");
        return;
      }

      const token = await getToken();
      if (!token) {
        throw new Error("Authentication token not available");
      }

      // If gym was selected or cleared, patch user's gym selection first
      // selectedGymId: string gym id, or null to proceed without gym
      try {
        await fetch("/api/users/gym", {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({ gymId: selectedGymId }),
        });
      } catch (e) {
        console.warn("Failed to update gym selection:", e);
      }

      const fitnessData = {
        clientId: user.id,
        height: parseFloat(fitnessProfile.height),
        weight: parseFloat(fitnessProfile.weight),
        goals: fitnessProfile.goals || undefined,
        fitnessLevel: fitnessProfile.fitnessLevel as
          | "beginner"
          | "intermediate"
          | "advanced",
        medicalConditions: fitnessProfile.medicalConditions || undefined,
        dietaryRestrictions: fitnessProfile.dietaryRestrictions || undefined,
        preferredWorkoutTime: fitnessProfile.preferredWorkoutTime as
          | "morning"
          | "afternoon"
          | "evening",
        workoutFrequency: parseInt(fitnessProfile.workoutFrequency) || 3,
      };

      await fitnessProfileApi.createFitnessProfile(fitnessData, token);
      router.replace("/(tabs)");
    } catch (error) {
      console.error("Error creating fitness profile:", error);
      Alert.alert(
        "Error",
        "Failed to create fitness profile. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleLevelSelect = (level: string) => {
    setFitnessProfile({ ...fitnessProfile, fitnessLevel: level });
  };

  const handleTimeSelect = (time: string) => {
    setFitnessProfile({ ...fitnessProfile, preferredWorkoutTime: time });
  };

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>Set Up Your Fitness Profile</Text>
      <Text style={styles.subtitle}>
        Help us personalize your fitness journey
      </Text>

      <View style={styles.form}>
        <Text style={styles.label}>Height (cm)</Text>
        <TextInput
          style={styles.input}
          value={fitnessProfile.height}
          onChangeText={(value) =>
            setFitnessProfile({ ...fitnessProfile, height: value })
          }
          keyboardType="numeric"
          placeholder="Enter height in cm"
        />

        <Text style={styles.label}>Weight (kg)</Text>
        <TextInput
          style={styles.input}
          value={fitnessProfile.weight}
          onChangeText={(value) =>
            setFitnessProfile({ ...fitnessProfile, weight: value })
          }
          keyboardType="numeric"
          placeholder="Enter weight in kg"
        />

        <Text style={styles.label}>Fitness Goals</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={fitnessProfile.goals}
          onChangeText={(value) =>
            setFitnessProfile({ ...fitnessProfile, goals: value })
          }
          multiline
          numberOfLines={3}
          placeholder="What are your fitness goals?"
        />

        <Text style={styles.label}>Fitness Level</Text>
        <View style={styles.buttonGroup}>
          {["beginner", "intermediate", "advanced"].map((level) => (
            <TouchableOpacity
              key={level}
              style={[
                styles.levelButton,
                fitnessProfile.fitnessLevel === level && styles.selectedButton,
              ]}
              onPress={() => handleLevelSelect(level)}
            >
              <Text
                style={[
                  styles.levelButtonText,
                  fitnessProfile.fitnessLevel === level &&
                    styles.selectedButtonText,
                ]}
              >
                {level.charAt(0).toUpperCase() + level.slice(1)}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        <Text style={styles.label}>Medical Conditions</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={fitnessProfile.medicalConditions}
          onChangeText={(value) =>
            setFitnessProfile({ ...fitnessProfile, medicalConditions: value })
          }
          multiline
          numberOfLines={3}
          placeholder="Any medical conditions we should know about?"
        />

        <Text style={styles.label}>Dietary Restrictions</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={fitnessProfile.dietaryRestrictions}
          onChangeText={(value) =>
            setFitnessProfile({
              ...fitnessProfile,
              dietaryRestrictions: value,
            })
          }
          multiline
          numberOfLines={3}
          placeholder="Any dietary restrictions?"
        />

        <Text style={styles.label}>Preferred Workout Time</Text>
        <View style={styles.buttonGroup}>
          {["morning", "afternoon", "evening"].map((time) => (
            <TouchableOpacity
              key={time}
              style={[
                styles.timeButton,
                fitnessProfile.preferredWorkoutTime === time &&
                  styles.selectedButton,
              ]}
              onPress={() => handleTimeSelect(time)}
            >
              <Text
                style={[
                  styles.timeButtonText,
                  fitnessProfile.preferredWorkoutTime === time &&
                    styles.selectedButtonText,
                ]}
              >
                {time.charAt(0).toUpperCase() + time.slice(1)}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        <Text style={styles.label}>Workouts per Week</Text>
        <TextInput
          style={styles.input}
          value={fitnessProfile.workoutFrequency}
          onChangeText={(value) =>
            setFitnessProfile({ ...fitnessProfile, workoutFrequency: value })
          }
          keyboardType="numeric"
          placeholder="Number of workouts per week"
        />

        <Text style={styles.label}>Select a Gym</Text>
        {gymsLoading ? (
          <ActivityIndicator />
        ) : (
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            style={{ marginBottom: 16 }}
          >
            <View style={{ flexDirection: "row" }}>
              <TouchableOpacity
                style={[
                  styles.levelButton,
                  selectedGymId === null && styles.selectedButton,
                ]}
                onPress={() => setSelectedGymId(null)}
              >
                <Text
                  style={[
                    styles.levelButtonText,
                    selectedGymId === null && styles.selectedButtonText,
                  ]}
                >
                  Proceed without gym
                </Text>
              </TouchableOpacity>
              {gyms.map((gym) => (
                <TouchableOpacity
                  key={gym.id}
                  style={[
                    styles.levelButton,
                    selectedGymId === gym.id && styles.selectedButton,
                  ]}
                  onPress={() => setSelectedGymId(gym.id)}
                >
                  <Text
                    style={[
                      styles.levelButtonText,
                      selectedGymId === gym.id && styles.selectedButtonText,
                    ]}
                  >
                    {gym.name}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        )}

        <TouchableOpacity
          style={styles.submitButton}
          onPress={handleSubmit}
          disabled={isSubmitting}
        >
          {isSubmitting ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text style={styles.submitButtonText}>Complete Setup</Text>
          )}
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f5f5f5",
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    textAlign: "center",
    marginTop: 40,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: "#666",
    textAlign: "center",
    marginBottom: 32,
  },
  form: {
    padding: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: "600",
    color: "#374151",
    marginBottom: 4,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
    backgroundColor: "white",
  },
  textArea: {
    height: 80,
    textAlignVertical: "top",
  },
  buttonGroup: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 16,
  },
  levelButton: {
    flex: 1,
    backgroundColor: "#f3f4f6",
    padding: 10,
    borderRadius: 8,
    marginHorizontal: 4,
    alignItems: "center",
  },
  timeButton: {
    flex: 1,
    backgroundColor: "#f3f4f6",
    padding: 10,
    borderRadius: 8,
    marginHorizontal: 4,
    alignItems: "center",
  },
  selectedButton: {
    backgroundColor: "#3b82f6",
  },
  levelButtonText: {
    color: "#374151",
    fontSize: 14,
    fontWeight: "500",
  },
  timeButtonText: {
    color: "#374151",
    fontSize: 14,
    fontWeight: "500",
  },
  selectedButtonText: {
    color: "white",
  },
  submitButton: {
    backgroundColor: "#3b82f6",
    padding: 16,
    borderRadius: 8,
    alignItems: "center",
    marginTop: 24,
  },
  submitButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "600",
  },
});
