import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { Card } from '../components';
import { colors, spacing, typography, borderRadius } from '../lib/theme';

interface Tip {
  id: string;
  title: string;
  content: string;
  category: string;
  icon: keyof typeof MaterialCommunityIcons.glyphMap;
}

const POTTERY_TIPS: Tip[] = [
  {
    id: '1',
    title: 'Wedging Clay',
    content: 'Always wedge your clay thoroughly before throwing to remove air bubbles and ensure consistent texture. Aim for 50-100 wedges.',
    category: 'Basics',
    icon: 'shape-plus',
  },
  {
    id: '2',
    title: 'Drying Time',
    content: 'Dry pieces slowly and evenly. Cover with plastic for controlled drying. Uneven drying leads to cracks!',
    category: 'Drying',
    icon: 'weather-sunny',
  },
  {
    id: '3',
    title: 'Bisque Firing',
    content: 'Bisque fire to Cone 04 (1945°F) for most clay bodies. This makes pieces porous and ready for glazing.',
    category: 'Firing',
    icon: 'fire',
  },
  {
    id: '4',
    title: 'Glaze Application',
    content: 'Apply 2-3 coats of glaze for best results. Too thin = bare spots, too thick = running. Test on tiles first!',
    category: 'Glazing',
    icon: 'brush',
  },
  {
    id: '5',
    title: 'Cone 6 is Popular',
    content: 'Cone 6 (2232°F) is the most common mid-range firing temperature. Great balance of durability and glaze options.',
    category: 'Firing',
    icon: 'flash',
  },
  {
    id: '6',
    title: 'Document Everything',
    content: 'Keep detailed notes! Record clay type, glaze brands, cone numbers, and firing schedules. This app helps!',
    category: 'Best Practice',
    icon: 'notebook-edit',
  },
  {
    id: '7',
    title: 'Test Tiles',
    content: 'Always make test tiles for new glaze combinations. Save yourself from ruined pieces!',
    category: 'Glazing',
    icon: 'flask',
  },
  {
    id: '8',
    title: 'Thickness Matters',
    content: 'Keep walls consistent - about 1/4 to 3/8 inch thick. Thinner walls fire more evenly.',
    category: 'Forming',
    icon: 'ruler',
  },
  {
    id: '9',
    title: 'Trimming Timing',
    content: 'Trim when leather-hard (firm but not dry). Too wet = distorts, too dry = cracks.',
    category: 'Trimming',
    icon: 'tools',
  },
  {
    id: '10',
    title: 'Foot Rings',
    content: 'Add a foot ring for stability and to elevate the piece from surfaces. Enhances the final look!',
    category: 'Trimming',
    icon: 'circle-double',
  },
  {
    id: '11',
    title: 'Reclaim Clay',
    content: 'Save all scraps! Dry completely, crush, add water, and wedge thoroughly to reuse. Nothing goes to waste.',
    category: 'Recycling',
    icon: 'recycle',
  },
  {
    id: '12',
    title: 'Never Mix Clay Bodies',
    content: 'Keep different clay types separate to avoid firing issues. Different clays shrink at different rates!',
    category: 'Recycling',
    icon: 'alert-circle',
  },
  {
    id: '13',
    title: 'Wire Tool',
    content: 'Use a twisted wire for cutting clay. Keep it taut for clean cuts and remove pieces from the wheel.',
    category: 'Tools',
    icon: 'content-cut',
  },
  {
    id: '14',
    title: 'Sponge Control',
    content: 'Don\'t over-sponge! Too much water weakens your piece and can cause collapse. Light touch is key.',
    category: 'Tools',
    icon: 'water',
  },
  {
    id: '15',
    title: 'Underglaze vs Glaze',
    content: 'Underglazes go on greenware or bisque, glazes only on bisque. Knowing the difference prevents mistakes!',
    category: 'Surface',
    icon: 'brush-variant',
  },
  {
    id: '16',
    title: 'Sgraffito Timing',
    content: 'Scratch through slip or underglaze when leather-hard for crisp, clean lines. Sharp tools work best!',
    category: 'Surface',
    icon: 'pencil',
  },
  {
    id: '17',
    title: 'Compression',
    content: 'Compress the bottom of thrown pieces to prevent cracking. Press firmly while centering to strengthen clay.',
    category: 'Forming',
    icon: 'weight',
  },
  {
    id: '18',
    title: 'S-Cracks Prevention',
    content: 'Pull from center outward when throwing to avoid S-cracks in the bottom. Consistent technique is crucial!',
    category: 'Forming',
    icon: 'rotate-3d-variant',
  },
  {
    id: '19',
    title: 'Silica Dust Safety',
    content: 'Always wet-clean clay dust. Never sweep dry - silica dust is harmful to lungs! Your health matters.',
    category: 'Safety',
    icon: 'air-filter',
  },
  {
    id: '20',
    title: 'Ventilation',
    content: 'Ensure good airflow when glazing and firing. Fumes can be toxic. Open windows or use exhaust fans!',
    category: 'Safety',
    icon: 'weather-windy',
  },
  {
    id: '21',
    title: 'Centering is Key',
    content: 'Take your time centering. A well-centered piece prevents wobbling and uneven walls throughout the throwing process.',
    category: 'Basics',
    icon: 'target',
  },
  {
    id: '22',
    title: 'Coning Up & Down',
    content: 'Cone clay up and down 2-3 times to align clay particles and strengthen the clay body before forming.',
    category: 'Basics',
    icon: 'arrow-up-down',
  },
  {
    id: '23',
    title: 'Slow Bisque Start',
    content: 'Start bisque firing slowly (150°F/hr to 400°F) to allow water to escape without cracking your pieces.',
    category: 'Firing',
    icon: 'speedometer-slow',
  },
  {
    id: '24',
    title: 'Pyrometric Cones',
    content: 'Always use witness cones! Digital controllers can fail. Cones don\'t lie about actual heatwork achieved.',
    category: 'Firing',
    icon: 'cone',
  },
  {
    id: '25',
    title: 'Kiln Loading',
    content: 'Stack bisque with 1" spacing for proper airflow. Touching pieces can stick together or crack during firing.',
    category: 'Firing',
    icon: 'view-grid',
  },
  {
    id: '26',
    title: 'Glaze Thickness Test',
    content: 'Dip a finger in wet glaze - you should see skin tone through it. Too opaque means it\'s too thick!',
    category: 'Glazing',
    icon: 'gesture-tap',
  },
  {
    id: '27',
    title: 'Wax Resist',
    content: 'Wax the bottom of pieces before glazing to prevent them from sticking to kiln shelves. Essential step!',
    category: 'Glazing',
    icon: 'candle',
  },
  {
    id: '28',
    title: 'Stir Your Glaze',
    content: 'Always stir glazes thoroughly before use! Glaze settles and consistency directly affects color and texture.',
    category: 'Glazing',
    icon: 'spoon-sugar',
  },
  {
    id: '29',
    title: 'Clay Storage',
    content: 'Store clay in airtight containers or wrap tightly in plastic. Add a damp towel for extra moisture retention.',
    category: 'Best Practice',
    icon: 'package-variant-closed',
  },
  {
    id: '30',
    title: 'Clean Water',
    content: 'Change throwing water frequently. Dirty water contaminates your clay with sediment and weakens it.',
    category: 'Best Practice',
    icon: 'water-check',
  },
  {
    id: '31',
    title: 'Handle Attachment',
    content: 'Attach handles to leather-hard pieces. Score surfaces, apply slip, and compress joints firmly for strength.',
    category: 'Forming',
    icon: 'handshake',
  },
  {
    id: '32',
    title: 'Warping Prevention',
    content: 'Dry thick and thin sections at the same rate by covering thinner areas with plastic. Prevents warping!',
    category: 'Drying',
    icon: 'shield-outline',
  },
];



const categoryColors: Record<string, string> = {
  'Basics': colors.textSecondary,
  'Drying': colors.drying,
  'Firing': colors.glazeFiring,
  'Glazing': colors.glazing,
  'Forming': colors.forming,
  'Trimming': colors.trimming,
  'Recycling': colors.success,
  'Tools': colors.accentDark,
  'Surface': colors.glazing,
  'Safety': colors.error,
  'Best Practice': colors.primary,
};

export const NewsScreen: React.FC = () => {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);

  const categories = Array.from(new Set(POTTERY_TIPS.map(tip => tip.category)));

  const filteredTips = selectedCategory
    ? POTTERY_TIPS.filter(tip => tip.category === selectedCategory)
    : POTTERY_TIPS;

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Tips & Tricks</Text>
        <Text style={styles.headerSubtitle}>Learn ceramics best practices</Text>
      </View>

      <View style={styles.filterContainer}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <TouchableOpacity
            style={[styles.filterButton, !selectedCategory && styles.filterButtonActive]}
            onPress={() => setSelectedCategory(null)}
          >
            <Text style={[styles.filterText, !selectedCategory && styles.filterTextActive]}>
              All
            </Text>
          </TouchableOpacity>
          {categories.map(category => (
            <TouchableOpacity
              key={category}
              style={[
                styles.filterButton,
                selectedCategory === category && styles.filterButtonActive,
              ]}
              onPress={() => setSelectedCategory(category)}
            >
              <Text
                style={[
                  styles.filterText,
                  selectedCategory === category && styles.filterTextActive,
                ]}
              >
                {category}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      <ScrollView style={styles.content} contentContainerStyle={styles.listContent}>
        {filteredTips.map((tip) => {
          const iconColor = categoryColors[tip.category] || colors.primary;
          return (
            <Card key={tip.id} style={styles.tipCard}>
              <View style={styles.tipHeader}>
                <MaterialCommunityIcons name={tip.icon} size={32} color={iconColor} />
                <View style={styles.tipHeaderText}>
                  <Text style={styles.tipTitle}>{tip.title}</Text>
                  <Text style={styles.tipCategory}>{tip.category}</Text>
                </View>
              </View>
              <Text style={styles.tipContent}>{tip.content}</Text>
            </Card>
          );
        })}
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    paddingBottom: spacing.lg,
    backgroundColor: colors.background,
    borderBottomWidth: 3,
    borderBottomColor: colors.primary,
  },
  headerTitle: {
    fontSize: typography.fontSize.xl,
    fontWeight: typography.fontWeight.bold,
    color: colors.primary,
    letterSpacing: 0.5,
    textTransform: 'uppercase',
    paddingHorizontal: spacing.lg,
  },
  headerSubtitle: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginTop: spacing.xs,
    paddingHorizontal: spacing.lg,
  },
  filterContainer: {
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
    backgroundColor: colors.background,
  },
  filterButton: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: borderRadius.full,
    borderWidth: 2,
    borderColor: colors.border,
    backgroundColor: colors.backgroundSecondary,
    marginRight: spacing.sm,
  },
  filterButtonActive: {
    borderColor: colors.primary,
    backgroundColor: colors.primaryLight,
  },
  filterText: {
    fontSize: typography.fontSize.xs,
    fontWeight: typography.fontWeight.bold,
    color: colors.textSecondary,
    letterSpacing: 0.3,
  },
  filterTextActive: {
    color: colors.text,
  },
  content: {
    flex: 1,
  },
  listContent: {
    paddingHorizontal: spacing.md,
    paddingTop: spacing.lg,
    paddingBottom: 100,
  },
  tipCard: {
    marginBottom: spacing.md,
  },
  tipHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: spacing.md,
    gap: spacing.md,
  },
  tipHeaderText: {
    flex: 1,
  },
  tipTitle: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    letterSpacing: 0.3,
    marginBottom: spacing.xs,
  },
  tipCategory: {
    fontSize: typography.fontSize.xs,
    fontWeight: typography.fontWeight.bold,
    color: colors.primary,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  tipContent: {
    fontSize: typography.fontSize.md,
    color: colors.textSecondary,
    lineHeight: 22,
  },
});
