import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  TextInput,
  Platform,
} from 'react-native';
import { useRouter, Stack } from 'expo-router';
import { useAuth } from '@clerk/clerk-expo';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { theme } from '../styles/theme';
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;
}

const GENDER_OPTIONS = [
  { label: 'Male', value: 'male', icon: 'male' },
  { label: 'Female', value: 'female', icon: 'female' },
  { label: 'Other', value: 'other', icon: 'transgender' },
];

const FITNESS_GOAL_OPTIONS = [
  { label: 'Weight Loss', value: 'weight_loss', icon: 'trending-down', color: theme.colors.danger },
  { label: 'Muscle Gain', value: 'muscle_gain', icon: 'barbell', color: theme.colors.primary },
  { label: 'Endurance', value: 'endurance', icon: 'bicycle', color: theme.colors.success },
  { label: 'Flexibility', value: 'flexibility', icon: 'body', color: theme.colors.purple },
  { label: 'General Fitness', value: 'general_fitness', icon: 'fitness', color: theme.colors.warning },
];

const ACTIVITY_LEVEL_OPTIONS = [
  { label: 'Sedentary', value: 'sedentary', description: 'Little to no exercise' },
  { label: 'Light', value: 'light', description: '1-3 days/week' },
  { label: 'Moderate', value: 'moderate', description: '3-5 days/week' },
  { label: 'Active', value: 'active', description: '6-7 days/week' },
  { label: 'Very Active', value: 'very_active', description: 'Intense daily training' },
];

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>({});

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

  const fetchProfile = async () => {
    try {
      setFetchingProfile(true);
      const token = await getToken();
      const response = await fetch(`${API_BASE_URL}/api/profile/fitness?userId=${userId}`, {
        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: Array.isArray(data.profile.fitnessGoals)
              ? data.profile.fitnessGoals[0]
              : (typeof data.profile.fitnessGoals === 'string'
                ? JSON.parse(data.profile.fitnessGoals)[0]
                : ''),
            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();

      // Prepare data with userId and convert fitnessGoal to fitnessGoals array
      const dataToSave = {
        userId: userId,
        height: profileData.height,
        weight: profileData.weight,
        age: profileData.age,
        gender: profileData.gender,
        fitnessGoals: profileData.fitnessGoal ? [profileData.fitnessGoal] : [],
        activityLevel: profileData.activityLevel,
        medicalConditions: profileData.medicalConditions,
        allergies: profileData.allergies,
        injuries: profileData.injuries,
      };

      const response = await fetch(`${API_BASE_URL}/api/profile/fitness`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(dataToSave),
      });

      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.error || '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={theme.colors.primary} />
      </View>
    );
  }

  return (
    <>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={styles.container}>
        {/* Header */}
        <LinearGradient colors={theme.gradients.primary} style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={() => router.back()}>
            <Ionicons name="arrow-back" size={24} color="#fff" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>Fitness Profile</Text>
          <View style={{ width: 40 }} />
        </LinearGradient>

        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
        >
          {/* Basic Information */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Basic Information</Text>
            <View style={styles.card}>
              <View style={styles.row}>
                <View style={styles.inputGroup}>
                  <Text style={styles.label}>Height (cm)</Text>
                  <View style={styles.inputContainer}>
                    <Ionicons name="resize-outline" size={20} color={theme.colors.gray400} />
                    <TextInput
                      style={styles.input}
                      value={profileData.height?.toString() || ''}
                      onChangeText={(text) =>
                        updateField('height', text ? parseFloat(text) : undefined)
                      }
                      keyboardType="decimal-pad"
                      placeholder="175"
                      placeholderTextColor={theme.colors.gray400}
                    />
                  </View>
                </View>
                <View style={styles.inputGroup}>
                  <Text style={styles.label}>Weight (kg)</Text>
                  <View style={styles.inputContainer}>
                    <Ionicons name="scale-outline" size={20} color={theme.colors.gray400} />
                    <TextInput
                      style={styles.input}
                      value={profileData.weight?.toString() || ''}
                      onChangeText={(text) =>
                        updateField('weight', text ? parseFloat(text) : undefined)
                      }
                      keyboardType="decimal-pad"
                      placeholder="70"
                      placeholderTextColor={theme.colors.gray400}
                    />
                  </View>
                </View>
              </View>
              <View style={styles.inputGroup}>
                <Text style={styles.label}>Age</Text>
                <View style={styles.inputContainer}>
                  <Ionicons name="calendar-outline" size={20} color={theme.colors.gray400} />
                  <TextInput
                    style={styles.input}
                    value={profileData.age?.toString() || ''}
                    onChangeText={(text) =>
                      updateField('age', text ? parseInt(text, 10) : undefined)
                    }
                    keyboardType="number-pad"
                    placeholder="25"
                    placeholderTextColor={theme.colors.gray400}
                  />
                </View>
              </View>
            </View>
          </View>

          {/* Gender Selection */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Gender</Text>
            <View style={styles.optionsRow}>
              {GENDER_OPTIONS.map((option) => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.optionCard,
                    profileData.gender === option.value && styles.optionCardActive,
                  ]}
                  onPress={() => updateField('gender', option.value)}
                >
                  <Ionicons
                    name={option.icon as any}
                    size={24}
                    color={
                      profileData.gender === option.value
                        ? theme.colors.primary
                        : theme.colors.gray400
                    }
                  />
                  <Text
                    style={[
                      styles.optionLabel,
                      profileData.gender === option.value && styles.optionLabelActive,
                    ]}
                  >
                    {option.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Fitness Goal */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Primary Fitness Goal</Text>
            <View style={styles.card}>
              {FITNESS_GOAL_OPTIONS.map((option, index) => (
                <React.Fragment key={option.value}>
                  <TouchableOpacity
                    style={styles.listItem}
                    onPress={() => updateField('fitnessGoal', option.value)}
                  >
                    <View style={[styles.iconCircle, { backgroundColor: `${option.color}20` }]}>
                      <Ionicons name={option.icon as any} size={20} color={option.color} />
                    </View>
                    <Text style={styles.listItemText}>{option.label}</Text>
                    {profileData.fitnessGoal === option.value && (
                      <Ionicons name="checkmark-circle" size={24} color={theme.colors.primary} />
                    )}
                  </TouchableOpacity>
                  {index < FITNESS_GOAL_OPTIONS.length - 1 && <View style={styles.divider} />}
                </React.Fragment>
              ))}
            </View>
          </View>

          {/* Activity Level */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Activity Level</Text>
            <View style={styles.card}>
              {ACTIVITY_LEVEL_OPTIONS.map((option, index) => (
                <React.Fragment key={option.value}>
                  <TouchableOpacity
                    style={styles.listItem}
                    onPress={() => updateField('activityLevel', option.value)}
                  >
                    <View style={{ flex: 1 }}>
                      <Text style={styles.listItemText}>{option.label}</Text>
                      <Text style={styles.listItemDescription}>{option.description}</Text>
                    </View>
                    {profileData.activityLevel === option.value && (
                      <Ionicons name="checkmark-circle" size={24} color={theme.colors.primary} />
                    )}
                  </TouchableOpacity>
                  {index < ACTIVITY_LEVEL_OPTIONS.length - 1 && <View style={styles.divider} />}
                </React.Fragment>
              ))}
            </View>
          </View>

          {/* Health Information */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Health Information (Optional)</Text>
            <View style={styles.card}>
              <View style={styles.inputGroup}>
                <Text style={styles.label}>Medical Conditions</Text>
                <TextInput
                  style={[styles.textArea]}
                  value={profileData.medicalConditions || ''}
                  onChangeText={(text) => updateField('medicalConditions', text)}
                  placeholder="e.g., Asthma, diabetes..."
                  placeholderTextColor={theme.colors.gray400}
                  multiline
                  numberOfLines={3}
                  textAlignVertical="top"
                />
              </View>
              <View style={styles.inputGroup}>
                <Text style={styles.label}>Allergies</Text>
                <TextInput
                  style={[styles.textArea]}
                  value={profileData.allergies || ''}
                  onChangeText={(text) => updateField('allergies', text)}
                  placeholder="e.g., Peanuts, latex..."
                  placeholderTextColor={theme.colors.gray400}
                  multiline
                  numberOfLines={3}
                  textAlignVertical="top"
                />
              </View>
              <View style={styles.inputGroup}>
                <Text style={styles.label}>Injuries</Text>
                <TextInput
                  style={[styles.textArea]}
                  value={profileData.injuries || ''}
                  onChangeText={(text) => updateField('injuries', text)}
                  placeholder="e.g., Previous knee injury..."
                  placeholderTextColor={theme.colors.gray400}
                  multiline
                  numberOfLines={3}
                  textAlignVertical="top"
                />
              </View>
            </View>
          </View>
        </ScrollView>

        {/* Save Button */}
        <View style={styles.footer}>
          <TouchableOpacity
            style={[styles.saveButton, loading && styles.saveButtonDisabled]}
            onPress={handleSave}
            disabled={loading}
          >
            <LinearGradient colors={theme.gradients.primary} style={styles.saveButtonGradient}>
              {loading ? (
                <ActivityIndicator color="#fff" />
              ) : (
                <>
                  <Ionicons name="checkmark-circle" size={20} color="#fff" />
                  <Text style={styles.saveButtonText}>Save Profile</Text>
                </>
              )}
            </LinearGradient>
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: theme.colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: Platform.OS === 'ios' ? 60 : 40,
    paddingBottom: 20,
    paddingHorizontal: 20,
  },
  backButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: theme.typography.fontSize['2xl'],
    fontWeight: theme.typography.fontWeight.bold,
    color: '#fff',
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
    paddingBottom: 100,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: theme.typography.fontSize.lg,
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.gray900,
    marginBottom: 12,
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: theme.borderRadius.xl,
    padding: 16,
    ...theme.shadows.subtle,
    borderWidth: 1,
    borderColor: theme.colors.gray100,
  },
  row: {
    flexDirection: 'row',
    gap: 12,
    marginBottom: 16,
  },
  inputGroup: {
    flex: 1,
    marginBottom: 16,
  },
  label: {
    fontSize: theme.typography.fontSize.sm,
    fontWeight: theme.typography.fontWeight.semibold,
    color: theme.colors.gray700,
    marginBottom: 8,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: theme.colors.gray50,
    borderRadius: theme.borderRadius.lg,
    borderWidth: 1,
    borderColor: theme.colors.gray200,
    paddingHorizontal: 12,
    gap: 8,
  },
  input: {
    flex: 1,
    paddingVertical: 12,
    fontSize: theme.typography.fontSize.base,
    color: theme.colors.gray900,
  },
  textArea: {
    backgroundColor: theme.colors.gray50,
    borderRadius: theme.borderRadius.lg,
    borderWidth: 1,
    borderColor: theme.colors.gray200,
    padding: 12,
    fontSize: theme.typography.fontSize.base,
    color: theme.colors.gray900,
    minHeight: 80,
  },
  optionsRow: {
    flexDirection: 'row',
    gap: 12,
  },
  optionCard: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: theme.borderRadius.lg,
    padding: 16,
    alignItems: 'center',
    gap: 8,
    borderWidth: 2,
    borderColor: theme.colors.gray200,
    ...theme.shadows.subtle,
  },
  optionCardActive: {
    borderColor: theme.colors.primary,
    backgroundColor: `${theme.colors.primary}10`,
  },
  optionLabel: {
    fontSize: theme.typography.fontSize.sm,
    fontWeight: theme.typography.fontWeight.medium,
    color: theme.colors.gray600,
  },
  optionLabelActive: {
    color: theme.colors.primary,
    fontWeight: theme.typography.fontWeight.bold,
  },
  listItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    gap: 12,
  },
  iconCircle: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listItemText: {
    flex: 1,
    fontSize: theme.typography.fontSize.base,
    fontWeight: theme.typography.fontWeight.medium,
    color: theme.colors.gray900,
  },
  listItemDescription: {
    fontSize: theme.typography.fontSize.xs,
    color: theme.colors.gray500,
    marginTop: 2,
  },
  divider: {
    height: 1,
    backgroundColor: theme.colors.gray100,
  },
  footer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 20,
    paddingBottom: Platform.OS === 'ios' ? 40 : 20,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: theme.colors.gray100,
    ...theme.shadows.medium,
  },
  saveButton: {
    borderRadius: theme.borderRadius.lg,
    overflow: 'hidden',
  },
  saveButtonGradient: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 16,
    gap: 8,
  },
  saveButtonDisabled: {
    opacity: 0.6,
  },
  saveButtonText: {
    fontSize: theme.typography.fontSize.base,
    fontWeight: theme.typography.fontWeight.bold,
    color: '#fff',
  },
});
