import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Alert,
  Image,
  TouchableOpacity,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import * as ImagePicker from 'expo-image-picker';
import { MaterialCommunityIcons } from '@expo/vector-icons'; // NEW
import { useNavigation, useRoute, RouteProp, useFocusEffect } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../navigation/types';
import { Project, Step } from '../types';
import {
  getProject,
  createProject,
  updateProject,
  deleteProject,
  getStepsByProject,
} from '../lib/db/repositories';
import { Button, Input, Card } from '../components';
import { colors, spacing, typography, stepTypeIcons, stepTypeLabels, borderRadius, stepTypeColors, shadows } from '../lib/theme';
import { formatDate } from '../lib/utils/datetime';
import { sortStepsByLogicalOrder, suggestNextStep } from '../lib/utils/stepOrdering';
import { useAuth } from '../contexts/AuthContext';

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'ProjectDetail'>;
type RouteProps = RouteProp<RootStackParamList, 'ProjectDetail'>;

export const ProjectDetailScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const route = useRoute<RouteProps>();
  const { user } = useAuth();
  const isNew = route.params.projectId === 'new';

  const [title, setTitle] = useState('');
  const [status, setStatus] = useState<Project['status']>('in_progress');
  const [tags, setTags] = useState('');
  const [coverImage, setCoverImage] = useState<string | null>(null);
  const [steps, setSteps] = useState<Step[]>([]);
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!isNew) {
      loadProject();
    }
  }, [route.params.projectId]);

  // Reload steps whenever screen comes into focus (for instant save display)
  useFocusEffect(
    React.useCallback(() => {
      if (!isNew) {
        console.log('ProjectDetail focused - reloading steps');
        loadSteps();
      }
    }, [isNew])
  );

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, [navigation]);

  const loadSteps = async () => {
    try {
      const projectSteps = await getStepsByProject(route.params.projectId);
      const sortedSteps = [...projectSteps].sort((a, b) =>
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
      setSteps(sortedSteps);
      console.log('✅ Steps reloaded, count:', sortedSteps.length);
    } catch (error) {
      console.error('Failed to reload steps:', error);
    }
  };

  const loadProject = async () => {
    try {
      const project = await getProject(route.params.projectId);
      if (project) {
        setTitle(project.title);
        setStatus(project.status);
        setTags(project.tags.join(', '));
        setCoverImage(project.coverImageUri || null);

        const projectSteps = await getStepsByProject(project.id);
        const sortedSteps = [...projectSteps].sort((a, b) =>
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        );
        setSteps(sortedSteps);
      }
    } catch (error) {
      console.error('Failed to load project:', error);
    } finally {
      setLoading(false);
    }
  };

  const takePhoto = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission needed', 'We need camera permissions to take photos');
      return;
    }

    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [4, 3],
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0]) {
      setCoverImage(result.assets[0].uri);
    }
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission needed', 'We need camera roll permissions to add photos');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: 'images',
      allowsEditing: true,
      aspect: [4, 3],
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0]) {
      setCoverImage(result.assets[0].uri);
    }
  };

  const handleAddCoverImage = () => {
    Alert.alert(
      'Add Cover Photo',
      'Choose a source',
      [
        { text: 'Camera', onPress: takePhoto },
        { text: 'Gallery', onPress: pickImage },
        { text: 'Cancel', style: 'cancel' },
      ]
    );
  };

  const handleSave = async () => {
    if (!title.trim()) {
      Alert.alert('Error', 'Please enter a project title');
      return;
    }

    if (!user) {
      Alert.alert('Error', 'User not authenticated');
      return;
    }

    setSaving(true);
    try {
      const tagArray = tags.split(',').map(t => t.trim()).filter(t => t);

      if (isNew) {
        await createProject(user.id, title, tagArray, status, coverImage || undefined);
      } else {
        await updateProject(route.params.projectId, {
          title,
          status,
          tags: tagArray,
          coverImageUri: coverImage || undefined,
        });
      }

      // Navigate to home after successful save
      navigation.navigate('MainTabs', { screen: 'Projects' });
    } catch (error) {
      console.error('Failed to save project:', error);
      Alert.alert('Error', 'Failed to save project');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = () => {
    Alert.alert(
      'Delete Project',
      'Are you sure you want to delete this project?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: async () => {
            await deleteProject(route.params.projectId);
            navigation.goBack();
          },
        },
      ]
    );
  };

  const handleAddStep = () => {
    navigation.navigate('StepEditor', { projectId: route.params.projectId });
  };

  const handleEditStep = (stepId: string) => {
    navigation.navigate('StepEditor', { projectId: route.params.projectId, stepId });
  };

  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <Text>Loading...</Text>
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={() => navigation.goBack()}>
          <MaterialCommunityIcons name="chevron-left" size={24} color={colors.text} />
          <Text style={styles.backButtonText}>Back</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Project Overview</Text>
      </View>

      <KeyboardAwareScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        enableOnAndroid={true}
        enableAutomaticScroll={true}
        extraScrollHeight={100}
        keyboardShouldPersistTaps="handled"
      >
        <Card>
          <Text style={styles.label}>Cover Image</Text>
          <TouchableOpacity style={styles.imagePicker} onPress={handleAddCoverImage}>
            {coverImage ? (
              <Image source={{ uri: coverImage }} style={styles.coverImagePreview} />
            ) : (
              <View style={styles.imagePlaceholder}>
                <MaterialCommunityIcons name="camera-plus-outline" size={48} color={colors.textSecondary} />
                <Text style={styles.imagePlaceholderLabel}>Add Cover Photo</Text>
              </View>
            )}
          </TouchableOpacity>

          <Input
            label="Project Title"
            value={title}
            onChangeText={setTitle}
            placeholder="Enter project name"
          />

          <Input
            label="Tags (comma-separated)"
            value={tags}
            onChangeText={setTags}
            placeholder="e.g., bowl, cone 6, blue glaze"
          />

          <Text style={styles.label}>Status</Text>
          <View style={styles.statusContainer}>
            <TouchableOpacity
              style={[
                styles.statusButton,
                styles.statusButtonInProgress,
                status === 'in_progress' && styles.statusButtonActive,
                status === 'in_progress' && styles.statusButtonInProgressActive,
              ]}
              onPress={() => setStatus('in_progress')}
            >
              <Text style={[
                styles.statusButtonText,
                status === 'in_progress' && styles.statusButtonTextActive
              ]}>
                In Progress
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[
                styles.statusButton,
                styles.statusButtonDone,
                status === 'done' && styles.statusButtonActive,
                status === 'done' && styles.statusButtonDoneActive,
              ]}
              onPress={() => setStatus('done')}
            >
              <Text style={[
                styles.statusButtonText,
                status === 'done' && styles.statusButtonTextActive
              ]}>
                Done
              </Text>
            </TouchableOpacity>
          </View>

          <Button
            title={isNew ? 'Create Project' : 'Save Changes'}
            onPress={handleSave}
            loading={saving}
            style={styles.sageButton}
          />
        </Card>

        {!isNew && (
          <>
            <View style={styles.stepsHeader}>
              <Text style={styles.sectionTitle}>Process Steps</Text>
              <Button
                title="Add Step"
                icon={<MaterialCommunityIcons name="plus" size={20} color={colors.buttonText} />}
                onPress={handleAddStep}
                size="sm"
                style={styles.sageButton}
              />
            </View>

            {steps.length > 0 && status === 'in_progress' && (() => {
              const nextStep = suggestNextStep(steps);
              return nextStep ? (
                <TouchableOpacity
                  activeOpacity={0.8}
                  onPress={() => navigation.navigate('StepEditor', {
                    projectId: route.params.projectId,
                    initialStepType: nextStep
                  })}
                >
                  <Card style={[styles.suggestionCard, { backgroundColor: '#F0F4E8' }]}>
                    <View style={styles.suggestionHeader}>
                      <MaterialCommunityIcons name="lightbulb-on-outline" size={20} color={colors.primaryDark} />
                      <Text style={[styles.suggestionTitle, { color: colors.primaryDark }]}>Suggested Next Step</Text>
                    </View>
                    <View style={styles.suggestionContent}>
                      <MaterialCommunityIcons name={stepTypeIcons[nextStep] as any} size={24} color={stepTypeColors[nextStep]} />
                      <Text style={[styles.suggestionStepLabel, { color: colors.text }]}>{stepTypeLabels[nextStep]}</Text>
                    </View>
                  </Card>
                </TouchableOpacity>
              ) : null;
            })()}

            {steps.length === 0 ? (
              <Card>
                <Text style={styles.emptyText}>No steps yet. Add your first step!</Text>
              </Card>
            ) : (
              <View style={styles.timeline}>
                {steps.map((step, index) => (
                  <View key={step.id} style={styles.timelineItem}>
                    {/* Timeline dot and line */}
                    <View style={styles.timelineLeft}>
                      <View style={styles.timelineDot}>
                        <MaterialCommunityIcons name={stepTypeIcons[step.type] as any} size={20} color={colors.background} />
                      </View>
                      {index < steps.length - 1 && <View style={styles.timelineLine} />}
                    </View>

                    {/* Step card */}
                    <TouchableOpacity
                      style={styles.timelineRight}
                      onPress={() => handleEditStep(step.id)}
                      activeOpacity={0.7}
                    >
                      <Card style={styles.stepCard}>
                        <View style={styles.stepHeader}>
                          <View style={styles.stepHeaderText}>
                            <Text style={styles.stepType}>{stepTypeLabels[step.type]}</Text>
                            {step.photoUris && step.photoUris.length > 0 && (
                              <Text style={styles.photoCount}>📷 {step.photoUris.length}</Text>
                            )}
                          </View>
                        </View>
                        <Text style={styles.stepDate}>{formatDate(step.createdAt)}</Text>
                        {step.notesMarkdown && (
                          <Text style={styles.stepNotes} numberOfLines={2}>
                            {step.notesMarkdown}
                          </Text>
                        )}
                      </Card>
                    </TouchableOpacity>
                  </View>
                ))}
              </View>
            )}

            <Button
              title="Delete Project"
              onPress={handleDelete}
              variant="outline"
              style={styles.terracottaButton}
              textStyle={styles.terracottaText}
            />
          </>
        )}
      </KeyboardAwareScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: colors.backgroundSecondary,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.md,
    backgroundColor: colors.backgroundSecondary,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderLight,
  },
  headerTitle: {
    flex: 1,
    textAlign: 'center',
    fontSize: 24,
    fontWeight: '800',
    color: colors.text,
  },
  backButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.card,
    borderRadius: borderRadius.full,
    paddingVertical: spacing.xs,
    paddingHorizontal: spacing.sm,
    paddingRight: spacing.md,
    ...shadows.sm,
    zIndex: 10, // Ensure it sits above the absolute title
  },
  backButtonText: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginLeft: -4,
  },
  container: {
    flex: 1,
  },
  content: {
    paddingHorizontal: spacing.md,
    paddingBottom: spacing.md,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  deleteButton: {
    marginTop: spacing.md,
  },
  stepsHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: spacing.lg,
    marginBottom: spacing.md,
  },
  sectionTitle: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.bold,
    color: colors.primary,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
  },
  timeline: {
    paddingTop: spacing.sm,
  },
  timelineItem: {
    flexDirection: 'row',
    marginBottom: spacing.md,
  },
  timelineLeft: {
    alignItems: 'center',
    width: 60,
    marginRight: spacing.md,
  },
  timelineDot: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    borderWidth: 3,
    borderColor: colors.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1,
  },
  timelineDotIcon: {
    fontSize: 20,
  },
  timelineLine: {
    width: 3,
    flex: 1,
    backgroundColor: colors.border,
    marginTop: spacing.xs,
    marginBottom: spacing.xs,
  },
  timelineRight: {
    flex: 1,
    paddingTop: spacing.xs,
  },
  stepCard: {
    marginBottom: 0,
  },
  stepHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
  },
  stepHeaderText: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  stepType: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    letterSpacing: 0.3,
  },
  photoCount: {
    fontSize: typography.fontSize.xs,
    color: colors.textSecondary,
    fontWeight: typography.fontWeight.bold,
  },
  stepDate: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginTop: spacing.xs,
  },
  stepNotes: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginTop: spacing.sm,
  },
  emptyText: {
    fontSize: typography.fontSize.md,
    color: colors.textSecondary,
    textAlign: 'center',
  },
  label: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    marginBottom: spacing.sm,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
  },
  imagePicker: {
    marginBottom: spacing.lg,
    borderRadius: borderRadius.md,
    overflow: 'hidden',
    borderWidth: 2,
    borderColor: colors.border,
  },
  coverImagePreview: {
    width: '100%',
    height: 200,
    backgroundColor: colors.backgroundSecondary,
  },
  imagePlaceholder: {
    width: '100%',
    height: 200,
    backgroundColor: colors.backgroundSecondary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  imagePlaceholderText: {
    fontSize: 48,
    marginBottom: spacing.sm,
  },
  imagePlaceholderLabel: {
    fontSize: typography.fontSize.md,
    color: colors.textSecondary,
    fontWeight: typography.fontWeight.bold,
  },
  statusContainer: {
    flexDirection: 'row',
    gap: spacing.sm,
    marginBottom: spacing.lg,
  },
  statusButton: {
    flex: 1,
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.sm,
    borderRadius: borderRadius.md,
    borderWidth: 2,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.backgroundSecondary,
  },
  statusButtonActive: {
    borderWidth: 4,
  },
  statusButtonInProgress: {
    borderColor: colors.primary,
  },
  statusButtonInProgressActive: {
    backgroundColor: '#E8E9E4', // Light sage tint
  },
  statusButtonDone: {
    borderColor: colors.success,
  },
  statusButtonDoneActive: {
    backgroundColor: '#D4E8C8', // Light green tint
  },
  statusButtonArchived: {
    borderColor: colors.textTertiary,
  },
  statusButtonText: {
    fontSize: typography.fontSize.xs,
    fontWeight: typography.fontWeight.bold,
    color: colors.textTertiary,
    letterSpacing: 0.2,
    textTransform: 'uppercase',
  },
  statusButtonTextActive: {
    color: colors.text,
    fontWeight: '900',
  },
  suggestionCard: {
    marginBottom: spacing.md,
    backgroundColor: colors.primaryLight,
    borderWidth: 2,
    borderColor: colors.primary,
  },
  suggestionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    marginBottom: spacing.sm,
  },
  suggestionIcon: {
    fontSize: 20,
  },
  suggestionTitle: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
  },
  suggestionContent: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
    paddingVertical: spacing.sm,
  },
  suggestionStepIcon: {
    fontSize: 28,
  },
  suggestionStepLabel: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
  },
  sageButton: {
    backgroundColor: '#8B9A7C',
    borderColor: '#7A896C',
  },
  terracottaButton: {
    borderColor: '#C5675C',
    backgroundColor: 'transparent',
  },
  terracottaText: {
    color: '#C5675C',
  },
});
