import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Modal,
  Alert,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../src/constants/colors';
import { api } from '../../src/services/api';

export default function PlansScreen() {
  const [activeTab, setActiveTab] = useState<'diet' | 'workout'>('diet');
  const [dietPlans, setDietPlans] = useState<any[]>([]);
  const [workoutPlans, setWorkoutPlans] = useState<any[]>([]);
  const [users, setUsers] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showDietModal, setShowDietModal] = useState(false);
  const [showWorkoutModal, setShowWorkoutModal] = useState(false);

  const [newDietPlan, setNewDietPlan] = useState({
    name: '',
    description: '',
    meals: [] as any[],
    total_calories: '',
  });

  const [newWorkoutPlan, setNewWorkoutPlan] = useState({
    name: '',
    description: '',
    exercises: [] as any[],
    duration_minutes: '',
  });

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

  const loadData = async () => {
    try {
      const [diets, workouts, usersData] = await Promise.all([
        api.getAllDietPlans(),
        api.getAllWorkoutPlans(),
        api.getAllUsers(),
      ]);
      setDietPlans(diets);
      setWorkoutPlans(workouts);
      setUsers(usersData);
    } catch (error) {
      console.error('Error loading plans:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await loadData();
    setRefreshing(false);
  };

  const handleCreateDietPlan = async () => {
    if (!newDietPlan.name) {
      Alert.alert('Error', 'Please enter a plan name');
      return;
    }

    try {
      await api.createDietPlan({
        ...newDietPlan,
        total_calories: newDietPlan.total_calories ? parseInt(newDietPlan.total_calories) : null,
        meals: newDietPlan.meals.length > 0 ? newDietPlan.meals : [
          { meal_type: 'breakfast', name: 'Breakfast', recipe: 'To be filled', calories: 400 },
          { meal_type: 'lunch', name: 'Lunch', recipe: 'To be filled', calories: 600 },
          { meal_type: 'dinner', name: 'Dinner', recipe: 'To be filled', calories: 500 },
        ],
      });
      setShowDietModal(false);
      setNewDietPlan({ name: '', description: '', meals: [], total_calories: '' });
      loadData();
    } catch (error) {
      Alert.alert('Error', 'Failed to create diet plan');
    }
  };

  const handleCreateWorkoutPlan = async () => {
    if (!newWorkoutPlan.name) {
      Alert.alert('Error', 'Please enter a plan name');
      return;
    }

    try {
      await api.createWorkoutPlan({
        ...newWorkoutPlan,
        duration_minutes: newWorkoutPlan.duration_minutes ? parseInt(newWorkoutPlan.duration_minutes) : null,
        exercises: newWorkoutPlan.exercises.length > 0 ? newWorkoutPlan.exercises : [
          { name: 'Warm-up', sets: 1, reps: 1, rest_seconds: 60 },
          { name: 'Main Exercise', sets: 3, reps: 10, rest_seconds: 90 },
          { name: 'Cool-down', sets: 1, reps: 1, rest_seconds: 0 },
        ],
      });
      setShowWorkoutModal(false);
      setNewWorkoutPlan({ name: '', description: '', exercises: [], duration_minutes: '' });
      loadData();
    } catch (error) {
      Alert.alert('Error', 'Failed to create workout plan');
    }
  };

  const handleDeleteDietPlan = (planId: string, planName: string) => {
    Alert.alert('Delete Plan', `Delete "${planName}"?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await api.deleteDietPlan(planId);
            loadData();
          } catch (error) {
            Alert.alert('Error', 'Failed to delete plan');
          }
        },
      },
    ]);
  };

  const handleDeleteWorkoutPlan = (planId: string, planName: string) => {
    Alert.alert('Delete Plan', `Delete "${planName}"?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await api.deleteWorkoutPlan(planId);
            loadData();
          } catch (error) {
            Alert.alert('Error', 'Failed to delete plan');
          }
        },
      },
    ]);
  };

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

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.header}>
        <Text style={styles.title}>Plans</Text>
        <TouchableOpacity
          style={styles.addButton}
          onPress={() => activeTab === 'diet' ? setShowDietModal(true) : setShowWorkoutModal(true)}
        >
          <Ionicons name="add" size={24} color={colors.text} />
        </TouchableOpacity>
      </View>

      {/* Tab Switcher */}
      <View style={styles.tabContainer}>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'diet' && styles.tabActive]}
          onPress={() => setActiveTab('diet')}
        >
          <Ionicons
            name="restaurant-outline"
            size={20}
            color={activeTab === 'diet' ? colors.primary : colors.textMuted}
          />
          <Text style={[styles.tabText, activeTab === 'diet' && styles.tabTextActive]}>
            Diet Plans
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'workout' && styles.tabActive]}
          onPress={() => setActiveTab('workout')}
        >
          <Ionicons
            name="barbell-outline"
            size={20}
            color={activeTab === 'workout' ? colors.primary : colors.textMuted}
          />
          <Text style={[styles.tabText, activeTab === 'workout' && styles.tabTextActive]}>
            Workouts
          </Text>
        </TouchableOpacity>
      </View>

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {activeTab === 'diet' ? (
          dietPlans.length === 0 ? (
            <View style={styles.emptyState}>
              <Ionicons name="restaurant-outline" size={64} color={colors.textMuted} />
              <Text style={styles.emptyText}>No diet plans yet</Text>
            </View>
          ) : (
            dietPlans.map((plan) => (
              <View key={plan.id} style={styles.planCard}>
                <View style={styles.planHeader}>
                  <View style={styles.planIcon}>
                    <Ionicons name="restaurant" size={24} color={colors.secondary} />
                  </View>
                  <View style={styles.planInfo}>
                    <Text style={styles.planName}>{plan.name}</Text>
                    <Text style={styles.planMeta}>
                      {plan.meals?.length || 0} meals • {plan.total_calories || 'N/A'} cal
                    </Text>
                  </View>
                  <TouchableOpacity
                    onPress={() => handleDeleteDietPlan(plan.id, plan.name)}
                  >
                    <Ionicons name="trash-outline" size={20} color={colors.error} />
                  </TouchableOpacity>
                </View>
                {plan.description && (
                  <Text style={styles.planDescription}>{plan.description}</Text>
                )}
                <Text style={styles.assignedLabel}>
                  Assigned to: {plan.assigned_to?.length || 0} client(s)
                </Text>
              </View>
            ))
          )
        ) : (
          workoutPlans.length === 0 ? (
            <View style={styles.emptyState}>
              <Ionicons name="barbell-outline" size={64} color={colors.textMuted} />
              <Text style={styles.emptyText}>No workout plans yet</Text>
            </View>
          ) : (
            workoutPlans.map((plan) => (
              <View key={plan.id} style={styles.planCard}>
                <View style={styles.planHeader}>
                  <View style={[styles.planIcon, { backgroundColor: 'rgba(59, 130, 246, 0.1)' }]}>
                    <Ionicons name="barbell" size={24} color={colors.info} />
                  </View>
                  <View style={styles.planInfo}>
                    <Text style={styles.planName}>{plan.name}</Text>
                    <Text style={styles.planMeta}>
                      {plan.exercises?.length || 0} exercises • {plan.duration_minutes || 'N/A'} min
                    </Text>
                  </View>
                  <TouchableOpacity
                    onPress={() => handleDeleteWorkoutPlan(plan.id, plan.name)}
                  >
                    <Ionicons name="trash-outline" size={20} color={colors.error} />
                  </TouchableOpacity>
                </View>
                {plan.description && (
                  <Text style={styles.planDescription}>{plan.description}</Text>
                )}
                <Text style={styles.assignedLabel}>
                  Assigned to: {plan.assigned_to?.length || 0} client(s)
                </Text>
              </View>
            ))
          )
        )}
      </ScrollView>

      {/* Diet Plan Modal */}
      <Modal visible={showDietModal} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>New Diet Plan</Text>
              <TouchableOpacity onPress={() => setShowDietModal(false)}>
                <Ionicons name="close" size={24} color={colors.text} />
              </TouchableOpacity>
            </View>
            <TextInput
              style={styles.input}
              placeholder="Plan Name *"
              placeholderTextColor={colors.textMuted}
              value={newDietPlan.name}
              onChangeText={(text) => setNewDietPlan({ ...newDietPlan, name: text })}
            />
            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="Description"
              placeholderTextColor={colors.textMuted}
              multiline
              numberOfLines={3}
              value={newDietPlan.description}
              onChangeText={(text) => setNewDietPlan({ ...newDietPlan, description: text })}
            />
            <TextInput
              style={styles.input}
              placeholder="Total Calories"
              placeholderTextColor={colors.textMuted}
              keyboardType="numeric"
              value={newDietPlan.total_calories}
              onChangeText={(text) => setNewDietPlan({ ...newDietPlan, total_calories: text })}
            />
            <TouchableOpacity style={styles.submitButton} onPress={handleCreateDietPlan}>
              <Text style={styles.submitButtonText}>Create Diet Plan</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {/* Workout Plan Modal */}
      <Modal visible={showWorkoutModal} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>New Workout Plan</Text>
              <TouchableOpacity onPress={() => setShowWorkoutModal(false)}>
                <Ionicons name="close" size={24} color={colors.text} />
              </TouchableOpacity>
            </View>
            <TextInput
              style={styles.input}
              placeholder="Plan Name *"
              placeholderTextColor={colors.textMuted}
              value={newWorkoutPlan.name}
              onChangeText={(text) => setNewWorkoutPlan({ ...newWorkoutPlan, name: text })}
            />
            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="Description"
              placeholderTextColor={colors.textMuted}
              multiline
              numberOfLines={3}
              value={newWorkoutPlan.description}
              onChangeText={(text) => setNewWorkoutPlan({ ...newWorkoutPlan, description: text })}
            />
            <TextInput
              style={styles.input}
              placeholder="Duration (minutes)"
              placeholderTextColor={colors.textMuted}
              keyboardType="numeric"
              value={newWorkoutPlan.duration_minutes}
              onChangeText={(text) => setNewWorkoutPlan({ ...newWorkoutPlan, duration_minutes: text })}
            />
            <TouchableOpacity style={styles.submitButton} onPress={handleCreateWorkoutPlan}>
              <Text style={styles.submitButtonText}>Create Workout Plan</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    paddingBottom: 12,
  },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
  },
  addButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  tabContainer: {
    flexDirection: 'row',
    paddingHorizontal: 20,
    marginBottom: 16,
    gap: 12,
  },
  tab: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    backgroundColor: colors.backgroundCard,
    borderRadius: 10,
    gap: 8,
  },
  tabActive: {
    backgroundColor: 'rgba(255, 107, 53, 0.1)',
    borderWidth: 1,
    borderColor: colors.primary,
  },
  tabText: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.textMuted,
  },
  tabTextActive: {
    color: colors.primary,
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  emptyState: {
    alignItems: 'center',
    paddingTop: 60,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
    marginTop: 16,
  },
  planCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  planHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  planIcon: {
    width: 48,
    height: 48,
    borderRadius: 12,
    backgroundColor: 'rgba(29, 185, 84, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  planInfo: {
    flex: 1,
  },
  planName: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
  },
  planMeta: {
    fontSize: 13,
    color: colors.textSecondary,
    marginTop: 2,
  },
  planDescription: {
    fontSize: 14,
    color: colors.textSecondary,
    marginTop: 12,
    lineHeight: 20,
  },
  assignedLabel: {
    fontSize: 12,
    color: colors.textMuted,
    marginTop: 12,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: colors.backgroundLight,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: 20,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
  },
  input: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: colors.text,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: colors.border,
  },
  textArea: {
    height: 80,
    textAlignVertical: 'top',
  },
  submitButton: {
    backgroundColor: colors.primary,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 8,
  },
  submitButtonText: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
  },
});
