import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, Alert, Image, TouchableOpacity, TextInput } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import * as ImagePicker from 'expo-image-picker';
import { useNavigation, useRoute, RouteProp, CommonActions } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { SafeAreaView } from 'react-native-safe-area-context';
import { RootStackParamList } from '../navigation/types';
import {
  StepType,
  WeightUnit,
  Weight,
  ProductionMethod,
  DimensionUnit,
  Dimensions,
  KilnType,
  KilnPosition,
  GlazeLayer,
  ApplicationMethod
} from '../types';
import { createStep, getStep, updateStep, deleteStep, getSettings } from '../lib/db/repositories';
import { getConeTemperature } from '../lib/utils';
import { Button, Input, Card, WeightInput, ButtonGrid, DimensionsInput, GlazeLayerCard } from '../components';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { colors, spacing, typography, borderRadius, stepTypeIcons, stepTypeColors, shadows } from '../lib/theme';
import { useAuth } from '../contexts/AuthContext';

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

const STEP_TYPES: { value: StepType; label: string }[] = [
  { value: 'forming', label: 'Forming' },
  { value: 'trimming', label: 'Trimming' },
  { value: 'drying', label: 'Drying' },
  { value: 'bisque_firing', label: 'Bisque Firing' },
  { value: 'glazing', label: 'Glazing' },
  { value: 'glaze_firing', label: 'Glaze Firing' },
  { value: 'misc', label: 'Misc' },
];

export const StepEditorScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const route = useRoute<RouteProps>();
  const { user } = useAuth();
  const { projectId, stepId } = route.params;
  const isEditing = !!stepId;

  // Refs for scrolling to glaze layers section
  const scrollViewRef = useRef<KeyboardAwareScrollView>(null);
  const glazeLayersSectionRef = useRef<View>(null);

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

  const [stepType, setStepType] = useState<StepType>(route.params.initialStepType || 'forming');
  const [notes, setNotes] = useState('');
  const [photos, setPhotos] = useState<string[]>([]);

  // User preferences
  const [tempUnit, setTempUnit] = useState<'F' | 'C'>('F');
  const [weightUnit, setWeightUnit] = useState<WeightUnit>('lb');
  const [dimensionUnit, setDimensionUnit] = useState<DimensionUnit>('in');

  // Forming fields
  const [clayBody, setClayBody] = useState('');
  const [clayWeight, setClayWeight] = useState<Weight | undefined>(undefined);
  const [productionMethod, setProductionMethod] = useState<ProductionMethod>('wheel');
  const [dimensions, setDimensions] = useState<Dimensions | undefined>(undefined);

  // Firing fields
  const [cone, setCone] = useState('');
  const [temperature, setTemperature] = useState('');
  const [duration, setDuration] = useState('');
  const [kilnNotes, setKilnNotes] = useState('');
  const [kilnType, setKilnType] = useState<KilnType | ''>('');
  const [kilnCustomName, setKilnCustomName] = useState('');
  const [kilnPosition, setKilnPosition] = useState<KilnPosition | ''>('');
  const [kilnPositionNotes, setKilnPositionNotes] = useState('');
  const [firingSchedule, setFiringSchedule] = useState('');

  // Glazing fields
  const [glazeLayers, setGlazeLayers] = useState<GlazeLayer[]>([]);
  const [customGlazeName, setCustomGlazeName] = useState('');
  const [coats, setCoats] = useState('2');
  const [applicationMethod, setApplicationMethod] = useState<ApplicationMethod>('brush');
  const [selectedGlazeIds, setSelectedGlazeIds] = useState<string[]>([]);
  const [mixNotes, setMixNotes] = useState('');

  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(isEditing);

  // Load user's preferences
  useEffect(() => {
    loadUserPreferences();
  }, [user]);

  const loadUserPreferences = async () => {
    if (!user) return;
    try {
      const settings = await getSettings(user.id);
      setTempUnit(settings.tempUnit);
      setWeightUnit(settings.weightUnit);
      setDimensionUnit(settings.unitSystem === 'metric' ? 'cm' : 'in');
    } catch (error) {
      console.error('Failed to load user preferences:', error);
    }
  };

  useEffect(() => {
    if (isEditing && stepId) {
      loadStep();
    }
  }, [stepId]);

  // Callback ref for receiving glaze selection from GlazePicker
  const glazeSelectionCallbackRef = useRef<((layers: GlazeLayer[]) => void) | null>(null);

  // Auto-save whenever any field changes
  useEffect(() => {
    if (loading) return;
    if (isEditing && stepId) {
      const timeoutId = setTimeout(async () => {
        try {
          // Prepare data...
          const stepData: any = {
            projectId,
            type: stepType,
            notesMarkdown: notes,
            photoUris: photos,
          };

          if (stepType === 'forming') {
            stepData.forming = {
              clayBody: clayBody || undefined,
              clayWeight: clayWeight,
              productionMethod: productionMethod,
              dimensions: dimensions,
            };
          } else if (stepType === 'bisque_firing' || stepType === 'glaze_firing') {
            stepData.firing = {
              cone: cone || undefined,
              temperature: temperature ? { value: parseInt(temperature), unit: tempUnit } : undefined,
              durationMinutes: duration ? parseInt(duration) : undefined,
              kilnNotes: kilnNotes || undefined,
              kilnType: kilnType || undefined,
              kilnCustomName: kilnCustomName || undefined,
              kilnPosition: kilnPosition || undefined,
              kilnPositionNotes: kilnPositionNotes || undefined,
              firingSchedule: firingSchedule || undefined,
            };
          } else if (stepType === 'glazing') {
            stepData.glazing = {
              glazeLayers: glazeLayers.length > 0 ? glazeLayers : undefined,
              glazeIds: selectedGlazeIds.length > 0 ? selectedGlazeIds : undefined,
              coats: coats ? parseInt(coats) : undefined,
              application: applicationMethod,
              mixNotes: mixNotes || undefined,
            };
          }

          await updateStep(stepId, stepData);
          console.log('⚡ Auto-saved changes');
        } catch (error) {
          console.error('Auto-save error:', error);
        }
      }, 1000);
      return () => clearTimeout(timeoutId);
    }
  }, [
    stepType, notes, photos,
    clayBody, clayWeight, productionMethod, dimensions,
    cone, temperature, duration, kilnNotes, kilnType, kilnCustomName, kilnPosition, kilnPositionNotes, firingSchedule,
    glazeLayers, coats, applicationMethod, selectedGlazeIds, mixNotes,
    isEditing, stepId, loading, projectId, tempUnit
  ]);

  const loadStep = async () => {
    try {
      const step = await getStep(stepId!);
      if (!step) {
        Alert.alert('Error', 'Step not found');
        navigation.goBack();
        return;
      }
      setStepType(step.type);
      setNotes(step.notesMarkdown || '');
      setPhotos(step.photoUris || []);

      if (step.type === 'forming') {
        const forming = (step as any).forming;
        if (forming) {
          setClayBody(forming.clayBody || '');
          setClayWeight(forming.clayWeight);
          setProductionMethod(forming.productionMethod || 'wheel');
          setDimensions(forming.dimensions);
        }
      } else if (step.type === 'bisque_firing' || step.type === 'glaze_firing') {
        const firing = (step as any).firing;
        if (firing) {
          setCone(firing.cone || '');
          setTemperature(firing.temperature?.value?.toString() || '');
          setDuration(firing.durationMinutes?.toString() || '');
          setKilnNotes(firing.kilnNotes || '');
          setKilnType(firing.kilnType || '');
          setKilnCustomName(firing.kilnCustomName || '');
          setKilnPosition(firing.kilnPosition || '');
          setKilnPositionNotes(firing.kilnPositionNotes || '');
          setFiringSchedule(firing.firingSchedule || '');
        }
      } else if (step.type === 'glazing') {
        const glazing = (step as any).glazing;
        if (glazing) {
          if (glazing.glazeLayers && glazing.glazeLayers.length > 0) {
            setGlazeLayers(glazing.glazeLayers);
          } else {
            setCoats(glazing.coats?.toString() || '2');
            setApplicationMethod(glazing.application || 'brush');
            setSelectedGlazeIds(glazing.glazeIds || []);
          }
          setMixNotes(glazing.mixNotes || '');
        }
      }
    } catch (error) {
      console.error('Failed to load step:', error);
      Alert.alert('Error', 'Failed to load step');
    } finally {
      setLoading(false);
    }
  };

  const handleConeChange = (value: string) => {
    setCone(value);
    const temp = getConeTemperature(value, tempUnit);
    if (temp) {
      setTemperature(temp.value.toString());
    }
  };

  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]) {
      setPhotos([...photos, 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]) {
      setPhotos([...photos, result.assets[0].uri]);
    }
  };

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

  const removePhoto = (index: number) => {
    setPhotos(photos.filter((_, i) => i !== index));
  };

  const handleAddFromCatalog = () => {
    glazeSelectionCallbackRef.current = (newLayers: GlazeLayer[]) => {
      setGlazeLayers(prevLayers => [...prevLayers, ...newLayers]);
      if (stepType !== 'glazing') {
        setStepType('glazing');
      }
      setTimeout(() => {
        if (glazeLayersSectionRef.current && scrollViewRef.current) {
          glazeLayersSectionRef.current.measure((x, y, width, height, pageX, pageY) => {
            if (pageY) {
              scrollViewRef.current?.scrollToPosition(0, Math.max(0, pageY - 100), true);
            }
          });
        }
      }, 200);
    };
    navigation.navigate('GlazePicker', {
      projectId,
      stepId,
      mode: 'add_layer',
      onGlazesSelected: glazeSelectionCallbackRef,
    });
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const stepData: any = {
        projectId,
        type: stepType,
        notesMarkdown: notes,
        photoUris: photos,
      };

      if (stepType === 'forming') {
        stepData.forming = {
          clayBody: clayBody || undefined,
          clayWeight: clayWeight,
          productionMethod: productionMethod,
          dimensions: dimensions,
        };
      } else if (stepType === 'bisque_firing' || stepType === 'glaze_firing') {
        stepData.firing = {
          cone: cone || undefined,
          temperature: temperature ? { value: parseInt(temperature), unit: tempUnit } : undefined,
          durationMinutes: duration ? parseInt(duration) : undefined,
          kilnNotes: kilnNotes || undefined,
          kilnType: kilnType || undefined,
          kilnCustomName: kilnCustomName || undefined,
          kilnPosition: kilnPosition || undefined,
          kilnPositionNotes: kilnPositionNotes || undefined,
          firingSchedule: firingSchedule || undefined,
        };
      } else if (stepType === 'glazing') {
        stepData.glazing = {
          glazeLayers: glazeLayers.length > 0 ? glazeLayers : undefined,
          glazeIds: selectedGlazeIds.length > 0 ? selectedGlazeIds : undefined,
          coats: coats ? parseInt(coats) : undefined,
          application: applicationMethod,
          mixNotes: mixNotes || undefined,
        };
      }

      if (isEditing) {
        await updateStep(stepId!, stepData);
      } else {
        await createStep(stepData);
      }

      navigation.dispatch(
        CommonActions.reset({
          index: 1,
          routes: [
            { name: 'MainTabs' },
            { name: 'ProjectDetail', params: { projectId } },
          ],
        })
      );
    } catch (error) {
      console.error('Failed to save step:', error);
      Alert.alert('Error', 'Failed to save step');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = () => {
    Alert.alert('Delete Step', 'Are you sure you want to delete this step?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await deleteStep(stepId!);
            navigation.goBack();
          } catch (error) {
            Alert.alert('Error', 'Failed to delete step');
          }
        },
      },
    ]);
  };

  const handleCancel = () => {
    navigation.goBack();
  };

  const renderFormingFields = () => {
    const productionMethods = [
      { value: 'wheel', label: 'Wheel' },
      { value: 'handbuilding', label: 'Handbuilding' },
      { value: 'casting', label: 'Casting' },
      { value: 'other', label: 'Other' },
    ];

    return (
      <>
        <Input
          label="Clay Body"
          value={clayBody}
          onChangeText={setClayBody}
          placeholder="e.g., B-Mix, Porcelain"
        />
        <WeightInput
          label="Clay Weight"
          value={clayWeight}
          onChange={setClayWeight}
          userPreferredUnit={weightUnit}
        />
        <Text style={styles.sectionLabel}>Production Method</Text>
        <ButtonGrid
          options={productionMethods}
          selectedValue={productionMethod}
          onSelect={(value) => setProductionMethod(value as ProductionMethod)}
          columns={2}
        />
        <DimensionsInput
          label="Dimensions"
          value={dimensions}
          onChange={setDimensions}
          userPreferredUnit={dimensionUnit}
        />
      </>
    );
  };

  const renderFiringFields = () => {
    const kilnTypes = [
      { value: 'electric', label: 'Electric' },
      { value: 'gas', label: 'Gas' },
      { value: 'raku', label: 'Raku' },
      { value: 'other', label: 'Other' },
    ];
    const kilnPositions = [
      { value: 'top', label: 'Top' },
      { value: 'middle', label: 'Middle' },
      { value: 'bottom', label: 'Bottom' },
      { value: 'other', label: 'Other' },
    ];

    return (
      <>
        <Input
          label="Cone"
          value={cone}
          onChangeText={handleConeChange}
          placeholder="e.g., 04, 6, 10"
        />
        <Input
          label={`Temperature (°${tempUnit})`}
          value={temperature}
          onChangeText={setTemperature}
          placeholder="Auto-filled from cone"
          keyboardType="numeric"
        />
        <Input
          label="Duration (minutes)"
          value={duration}
          onChangeText={setDuration}
          placeholder="Total firing time"
          keyboardType="numeric"
        />
        <Text style={styles.sectionLabel}>Kiln Type</Text>
        <ButtonGrid
          options={kilnTypes}
          selectedValue={kilnType}
          onSelect={(value) => setKilnType(value as KilnType)}
          columns={2}
        />
        {kilnType === 'other' && (
          <Input
            label="Custom Kiln Name"
            value={kilnCustomName}
            onChangeText={setKilnCustomName}
            placeholder="Enter kiln name"
          />
        )}
        <Text style={styles.sectionLabel}>Position in Kiln</Text>
        <ButtonGrid
          options={kilnPositions}
          selectedValue={kilnPosition}
          onSelect={(value) => setKilnPosition(value as KilnPosition)}
          columns={2}
        />
        {kilnPosition === 'other' && (
          <Input
            label="Position Notes"
            value={kilnPositionNotes}
            onChangeText={setKilnPositionNotes}
            placeholder="Describe position"
          />
        )}
        <Input
          label="Firing Schedule"
          value={firingSchedule}
          onChangeText={setFiringSchedule}
          placeholder="Ramp, holds, cooling, etc."
          multiline
          numberOfLines={4}
        />
        <Input
          label="Kiln Notes"
          value={kilnNotes}
          onChangeText={setKilnNotes}
          placeholder="Additional notes"
          multiline
        />
      </>
    );
  };

  const renderGlazingFields = () => {
    const handleAddCustomGlaze = () => {
      if (!customGlazeName.trim()) return;
      const newLayer: GlazeLayer = {
        customGlazeName: customGlazeName.trim(),
        application: 'brush',
        position: 'entire',
        coats: 2,
        notes: '',
      };
      setGlazeLayers([...glazeLayers, newLayer]);
      setCustomGlazeName('');
    };

    const handleUpdateLayer = (index: number, updatedLayer: GlazeLayer) => {
      const newLayers = [...glazeLayers];
      newLayers[index] = updatedLayer;
      setGlazeLayers(newLayers);
    };

    const handleRemoveLayer = (index: number) => {
      setGlazeLayers(glazeLayers.filter((_, i) => i !== index));
    };

    return (
      <>
        <View ref={glazeLayersSectionRef}>
          <Text style={styles.sectionLabel}>Glaze Layers</Text>
          {glazeLayers.map((layer, index) => (
            <GlazeLayerCard
              key={index}
              layer={layer}
              layerNumber={index + 1}
              onUpdate={(updated) => handleUpdateLayer(index, updated)}
              onRemove={() => handleRemoveLayer(index)}
            />
          ))}
        </View>

        <View style={styles.addGlazeContainer}>
          <Text style={styles.sectionLabel}>Add Custom Glaze</Text>
          <View style={styles.customGlazeRow}>
            <TextInput
              style={styles.customGlazeInput}
              value={customGlazeName}
              onChangeText={setCustomGlazeName}
              placeholder="Enter glaze name"
              placeholderTextColor={colors.textSecondary}
            />
            <Button
              title="Add"
              onPress={handleAddCustomGlaze}
              variant="primary"
              size="sm"
            />
          </View>
        </View>

        <Button
          title="Add from Catalog"
          onPress={handleAddFromCatalog}
          variant="outline"
          style={styles.catalogButton}
        />

        <Input
          label="Mix Notes"
          value={mixNotes}
          onChangeText={setMixNotes}
          placeholder="Notes about glaze mixing or combination"
          multiline
          numberOfLines={3}
        />

        <Text style={styles.note}>
          {glazeLayers.length === 0
            ? 'Add glaze layers using custom names or from catalog'
            : `${glazeLayers.length} layer${glazeLayers.length > 1 ? 's' : ''} added`}
        </Text>
      </>
    );
  };

  const stepTypeOptions = STEP_TYPES.map(type => ({
    ...type,
    icon: (
      <MaterialCommunityIcons
        name={stepTypeIcons[type.value] as any}
        size={24}
        color={stepType === type.value ? colors.buttonText : stepTypeColors[type.value]}
      />
    )
  }));

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={handleCancel}>
          <MaterialCommunityIcons name="chevron-left" size={24} color={colors.text} />
          <Text style={styles.backButtonText}>Back</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>{isEditing ? 'Edit Step' : 'Add Step'}</Text>
      </View>

      <KeyboardAwareScrollView
        ref={scrollViewRef}
        style={styles.container}
        contentContainerStyle={styles.content}
        enableOnAndroid={true}
        enableAutomaticScroll={true}
        extraScrollHeight={100}
        keyboardShouldPersistTaps="handled"
      >
        <Card>
          <Text style={styles.sectionLabel}>Step Type</Text>
          <ButtonGrid
            options={stepTypeOptions}
            selectedValue={stepType}
            onSelect={(value) => setStepType(value as StepType)}
            columns={2}
          />

          {stepType === 'forming' && renderFormingFields()}
          {(stepType === 'bisque_firing' || stepType === 'glaze_firing') && renderFiringFields()}
          {stepType === 'glazing' && renderGlazingFields()}

          <Text style={styles.sectionLabel}>Photos</Text>
          <View style={styles.photosContainer}>
            {photos.map((uri, index) => (
              <View key={index} style={styles.photoWrapper}>
                <Image source={{ uri }} style={styles.photo} />
                <TouchableOpacity
                  style={styles.removePhotoButton}
                  onPress={() => removePhoto(index)}
                >
                  <Text style={styles.removePhotoText}>✕</Text>
                </TouchableOpacity>
              </View>
            ))}
            <TouchableOpacity style={styles.addPhotoButton} onPress={handleAddPhoto}>
              <Text style={styles.addPhotoIcon}>📷</Text>
              <Text style={styles.addPhotoText}>Add Photo</Text>
            </TouchableOpacity>
          </View>

          <Input
            label="Notes"
            value={notes}
            onChangeText={(text) => {
              if (text.length <= 5000) {
                setNotes(text);
              }
            }}
            placeholder="Add notes about this step (max 5000 characters)"
            multiline
            numberOfLines={8}
          />
          <Text style={styles.charCount}>
            {notes.length}/5000 characters
          </Text>

          <Button
            title={isEditing ? "Update Step" : "Save Step"}
            onPress={handleSave}
            loading={saving}
            style={styles.saveButton}
          />
          {isEditing && (
            <Button
              title="Delete Step"
              onPress={handleDelete}
              variant="outline"
              style={styles.deleteButtonInSticky}
            />
          )}
        </Card>
      </KeyboardAwareScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center', // content centered horizontally via absolute positioning
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    backgroundColor: colors.background,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    position: 'relative', // Context for absolute children
  },
  headerTitle: {
    position: 'absolute',
    left: 0,
    right: 0,
    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,
  },
  backButtonText: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginLeft: -4,
  },
  container: {
    flex: 1,
    backgroundColor: colors.backgroundSecondary,
  },
  content: {
    padding: spacing.md,
    paddingBottom: spacing.xxl,
  },
  sectionLabel: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    marginBottom: spacing.sm,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
    marginTop: spacing.md,
  },
  note: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    fontStyle: 'italic',
    marginTop: spacing.sm,
  },
  typeGrid: {
    marginBottom: 120, // Much larger separation as requested
  },
  photosContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
    marginBottom: spacing.lg,
  },
  photoWrapper: {
    position: 'relative',
    width: 100,
    height: 100,
  },
  photo: {
    width: '100%',
    height: '100%',
    borderRadius: borderRadius.md,
    borderWidth: 2,
    borderColor: colors.border,
  },
  removePhotoButton: {
    position: 'absolute',
    top: -8,
    right: -8,
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: colors.error,
    justifyContent: 'center',
    alignItems: 'center',
  },
  removePhotoText: {
    color: colors.background,
    fontSize: 14,
    fontWeight: 'bold',
  },
  addPhotoButton: {
    width: 100,
    height: 100,
    borderRadius: borderRadius.md,
    borderWidth: 2,
    borderColor: colors.border,
    borderStyle: 'dashed',
    backgroundColor: colors.backgroundSecondary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  addPhotoIcon: {
    fontSize: 32,
    marginBottom: spacing.xs,
  },
  addPhotoText: {
    fontSize: typography.fontSize.xs,
    color: colors.textSecondary,
    fontWeight: typography.fontWeight.bold,
  },
  saveButton: {
    marginTop: spacing.md,
  },
  deleteButtonInSticky: {
    marginTop: spacing.md,
  },
  addGlazeContainer: {
    marginBottom: spacing.md,
  },
  customGlazeRow: {
    flexDirection: 'row',
    gap: spacing.sm,
    alignItems: 'flex-end',
  },
  customGlazeInput: {
    flex: 1,
    height: 40,
    borderWidth: 2,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.sm,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.md,
    color: colors.text,
  },
  catalogButton: {
    marginBottom: spacing.md,
  },
  charCount: {
    fontSize: typography.fontSize.xs,
    color: colors.textSecondary,
    textAlign: 'right',
    marginTop: spacing.xs,
    marginBottom: spacing.md,
  },
});
