import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
} from "react-native";
import { useRouter } from "expo-router";
import { useAuth } from "@clerk/clerk-expo";
import { Ionicons } from "@expo/vector-icons";
import { Input } from "../components/Input";
import { Picker } from "../components/Picker";
import { API_BASE_URL } from "../config/api";

interface FitnessProfileData {
  height?: number;
  weight?: number;
  age?: number;
  gender?: string;
  fitnessGoal?: string;
  activityLevel?: string;
  medicalConditions?: string;
  allergies?: string;
  injuries?: string;
}

export default function FitnessProfileScreen() {
  const router = useRouter();
  const { userId, getToken } = useAuth();
  const [loading, setLoading] = useState(false);
  const [fetchingProfile, setFetchingProfile] = useState(true);
  const [profileData, setProfileData] = useState<FitnessProfileData>({});

  const genderOptions = [
    { label: "Male", value: "male" },
    { label: "Female", value: "female" },
    { label: "Other", value: "other" },
    { label: "Prefer not to say", value: "prefer_not_to_say" },
  ];

  const fitnessGoalOptions = [
    { label: "Weight Loss", value: "weight_loss" },
    { label: "Muscle Gain", value: "muscle_gain" },
    { label: "Endurance", value: "endurance" },
    { label: "Flexibility", value: "flexibility" },
    { label: "General Fitness", value: "general_fitness" },
  ];

  const activityLevelOptions = [
    { label: "Sedentary", value: "sedentary" },
    { label: "Lightly Active", value: "lightly_active" },
    { label: "Moderately Active", value: "moderately_active" },
    { label: "Very Active", value: "very_active" },
    { label: "Extremely Active", value: "extremely_active" },
  ];

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

  const fetchProfile = async () => {
    try {
      setFetchingProfile(true);
      const token = await getToken();
      const apiUrl = `${API_BASE_URL}` || "http://localhost:3000";
      const response = await fetch(`${apiUrl}/api/fitness-profile`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        if (data.profile) {
          setProfileData({
            height: data.profile.height,
            weight: data.profile.weight,
            age: data.profile.age,
            gender: data.profile.gender || "",
            fitnessGoal: data.profile.fitnessGoal || "",
            activityLevel: data.profile.activityLevel || "",
            medicalConditions: data.profile.medicalConditions || "",
            allergies: data.profile.allergies || "",
            injuries: data.profile.injuries || "",
          });
        }
      }
    } catch (error) {
      console.error("Error fetching profile:", error);
    } finally {
      setFetchingProfile(false);
    }
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      const token = await getToken();
      const apiUrl = `${API_BASE_URL}/api/fitness-profile` || "http://localhost:3000";

      const response = await fetch(`${apiUrl}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(profileData),
      });

      if (response.ok) {
        Alert.alert("Success", "Fitness profile saved successfully!", [
          { text: "OK", onPress: () => router.back() },
        ]);
      } else {
        const error = await response.json();
        Alert.alert("Error", error.message || "Failed to save profile");
      }
    } catch (error) {
      console.error("Error saving profile:", error);
      Alert.alert("Error", "Failed to save fitness profile");
    } finally {
      setLoading(false);
    }
  };

  const updateField = (field: keyof FitnessProfileData, value: any) => {
    setProfileData((prev) => ({ ...prev, [field]: value }));
  };

  if (fetchingProfile) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#2563eb" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
        >
          <Ionicons name="arrow-back" size={24} color="#1f2937" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Fitness Profile</Text>
        <View style={styles.headerSpacer} />
      </View>

      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.content}>
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Basic Information</Text>

            <Input
              label="Height (cm)"
              value={profileData.height?.toString() || ""}
              onChangeText={(text) =>
                updateField("height", text ? parseFloat(text) : undefined)
              }
              keyboardType="decimal-pad"
              placeholder="e.g., 175"
            />

            <Input
              label="Weight (kg)"
              value={profileData.weight?.toString() || ""}
              onChangeText={(text) =>
                updateField("weight", text ? parseFloat(text) : undefined)
              }
              keyboardType="decimal-pad"
              placeholder="e.g., 70"
            />

            <Input
              label="Age"
              value={profileData.age?.toString() || ""}
              onChangeText={(text) =>
                updateField("age", text ? parseInt(text, 10) : undefined)
              }
              keyboardType="number-pad"
              placeholder="e.g., 25"
            />

            <Picker
              label="Gender"
              value={profileData.gender || ""}
              onValueChange={(value) => updateField("gender", value)}
              items={genderOptions}
            />
          </View>

          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Fitness Goals</Text>

            <Picker
              label="Primary Goal"
              value={profileData.fitnessGoal || ""}
              onValueChange={(value) => updateField("fitnessGoal", value)}
              items={fitnessGoalOptions}
            />

            <Picker
              label="Activity Level"
              value={profileData.activityLevel || ""}
              onValueChange={(value) => updateField("activityLevel", value)}
              items={activityLevelOptions}
            />
          </View>

          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Health Information</Text>

            <Input
              label="Medical Conditions (optional)"
              value={profileData.medicalConditions || ""}
              onChangeText={(text) => updateField("medicalConditions", text)}
              placeholder="e.g., Asthma, diabetes..."
              multiline
              numberOfLines={3}
              style={styles.textArea}
            />

            <Input
              label="Allergies (optional)"
              value={profileData.allergies || ""}
              onChangeText={(text) => updateField("allergies", text)}
              placeholder="e.g., Peanuts, latex..."
              multiline
              numberOfLines={3}
              style={styles.textArea}
            />

            <Input
              label="Injuries (optional)"
              value={profileData.injuries || ""}
              onChangeText={(text) => updateField("injuries", text)}
              placeholder="e.g., Previous knee injury..."
              multiline
              numberOfLines={3}
              style={styles.textArea}
            />
          </View>

          <TouchableOpacity
            style={[styles.saveButton, loading && styles.saveButtonDisabled]}
            onPress={handleSave}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="white" />
            ) : (
              <>
                <Ionicons
                  name="checkmark-circle-outline"
                  size={20}
                  color="white"
                />
                <Text style={styles.saveButtonText}>Save Profile</Text>
              </>
            )}
          </TouchableOpacity>
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f9fafb",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f9fafb",
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingTop: 60,
    paddingBottom: 16,
    backgroundColor: "white",
    borderBottomWidth: 1,
    borderBottomColor: "#e5e7eb",
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#1f2937",
  },
  headerSpacer: {
    width: 32,
  },
  scrollView: {
    flex: 1,
  },
  content: {
    padding: 20,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: "#1f2937",
    marginBottom: 16,
  },
  textArea: {
    height: 80,
    textAlignVertical: "top",
    paddingTop: 12,
  },
  saveButton: {
    backgroundColor: "#2563eb",
    borderRadius: 8,
    padding: 16,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 8,
    marginBottom: 40,
  },
  saveButtonDisabled: {
    opacity: 0.6,
  },
  saveButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
});
