import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput } from 'react-native';
import { Card } from './Card';
import { Button } from './Button';
import { Picker } from './Picker';
import { ButtonGrid } from './ButtonGrid'; // NEW
import { colors, spacing, typography, borderRadius } from '../lib/theme';
import { GlazeLayer, ApplicationMethod, GlazePosition } from '../types';
import { getGlaze } from '../lib/db/repositories';

interface GlazeLayerCardProps {
  layer: GlazeLayer;
  layerNumber: number;
  onUpdate: (layer: GlazeLayer) => void;
  onRemove: () => void;
}

export const GlazeLayerCard: React.FC<GlazeLayerCardProps> = ({
  layer,
  layerNumber,
  onUpdate,
  onRemove,
}) => {
  const [glazeName, setGlazeName] = useState<string>(
    layer.customGlazeName || layer.glazeId || 'Unknown Glaze'
  );

  // Load glaze name if we have a glazeId
  useEffect(() => {
    if (layer.glazeId && !layer.customGlazeName) {
      loadGlazeName();
    }
  }, [layer.glazeId]);

  const loadGlazeName = async () => {
    if (!layer.glazeId) return;

    try {
      const glaze = await getGlaze(layer.glazeId);
      if (glaze) {
        setGlazeName(`${glaze.brand} ${glaze.name}`);
      }
    } catch (error) {
      console.error('Failed to load glaze:', error);
      setGlazeName(layer.glazeId); // Fallback to ID
    }
  };

  const handleApplicationChange = (value: string) => {
    onUpdate({ ...layer, application: value as ApplicationMethod });
  };

  const handlePositionChange = (value: string) => {
    onUpdate({ ...layer, position: value as GlazePosition });
  };

  const handleCoatsChange = (text: string) => {
    const coats = parseInt(text);
    onUpdate({ ...layer, coats: isNaN(coats) ? undefined : coats });
  };

  const handleNotesChange = (text: string) => {
    onUpdate({ ...layer, notes: text || undefined });
  };

  return (
    <Card style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.layerNumber}>Layer {layerNumber}</Text>
        <Button
          title="Remove"
          onPress={onRemove}
          variant="outline"
          size="sm"
        />
      </View>

      <Text style={styles.glazeName}>{glazeName}</Text>

      <Text style={styles.label}>Application Method</Text>
      <ButtonGrid
        options={[
          { value: 'brush', label: 'Brushing' },
          { value: 'dip', label: 'Dipping' },
          { value: 'pour', label: 'Pouring' },
          { value: 'spray', label: 'Spraying' },
          { value: 'other', label: 'Other' },
        ]}
        selectedValue={layer.application}
        onSelect={handleApplicationChange}
        columns={2}
      />

      <Text style={styles.label}>Position on Piece</Text>
      <ButtonGrid
        options={[
          { value: 'entire', label: 'Entire Piece' },
          { value: 'top', label: 'Top' },
          { value: 'middle', label: 'Middle' },
          { value: 'bottom', label: 'Bottom' },
          { value: 'inside', label: 'Inside' },
          { value: 'outside', label: 'Outside' },
          { value: 'other', label: 'Other' },
        ]}
        selectedValue={layer.position}
        onSelect={handlePositionChange}
        columns={2}
      />

      <View style={styles.coatsContainer}>
        <Text style={styles.label}>Coats</Text>
        <TextInput
          style={styles.coatsInput}
          value={layer.coats?.toString() || ''}
          onChangeText={handleCoatsChange}
          placeholder="1"
          keyboardType="number-pad"
        />
      </View>

      <View style={styles.notesContainer}>
        <Text style={styles.label}>Layer Notes</Text>
        <TextInput
          style={styles.notesInput}
          value={layer.notes || ''}
          onChangeText={handleNotesChange}
          placeholder="Notes for this layer"
          multiline
          numberOfLines={2}
        />
      </View>
    </Card>
  );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: spacing.md,
    padding: spacing.md,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  layerNumber: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.semiBold,
    color: colors.primary,
  },
  glazeName: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginBottom: spacing.md,
  },
  label: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginBottom: spacing.xs,
  },
  coatsContainer: {
    marginBottom: spacing.md,
  },
  coatsInput: {
    height: 48,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.md,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.md,
    color: colors.text,
  },
  notesContainer: {
    marginBottom: 0,
  },
  notesInput: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    padding: spacing.sm,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.sm,
    color: colors.text,
    minHeight: 60,
  },
});
