import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, FlatList, Alert } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { useResponsive } from '../../hooks/useResponsive';
import { useToast } from '../../context/ToastContext';
import { materialService } from '../../services/materialService';
import { MaterialCategory } from '../../types';
import { colors, spacing, radii } from '../../theme';

export default function CategoryManageScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();
  const [categories, setCategories] = useState<MaterialCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [newName, setNewName] = useState('');
  const [editTarget, setEditTarget] = useState<MaterialCategory | null>(null);
  const [editName, setEditName] = useState('');
  const [saving, setSaving] = useState(false);

  const loadData = async () => {
    try {
      const data = await materialService.listCategories();
      setCategories(data);
    } catch {} finally { setLoading(false); }
  };

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

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setSaving(true);
    try {
      await materialService.createCategory(newName.trim());
      toast('Category created', 'success');
      setNewName('');
      loadData();
    } catch (e: any) {
      toast(e.response?.data?.message || 'Failed to create', 'error');
    } finally { setSaving(false); }
  };

  const handleUpdate = async () => {
    if (!editTarget || !editName.trim()) return;
    setSaving(true);
    try {
      await materialService.updateCategory(editTarget.id, editName.trim());
      toast('Category updated', 'success');
      setEditTarget(null);
      setEditName('');
      loadData();
    } catch (e: any) {
      toast(e.response?.data?.message || 'Failed to update', 'error');
    } finally { setSaving(false); }
  };

  const handleDelete = (cat: MaterialCategory) => {
    Alert.alert('Delete Category', `Delete "${cat.name}"?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete', style: 'destructive',
        onPress: async () => {
          try {
            await materialService.removeCategory(cat.id);
            toast('Category deleted', 'success');
            loadData();
          } catch { toast('Failed to delete', 'error'); }
        }
      }
    ]);
  };

  return (
    <ScreenContainer
      title="Manage Categories"
      subtitle={`${categories.length} categories`}
      onBack={() => navigation.goBack()}
      loading={loading}
      scroll={true}
      contentPadding={contentPadding}
    >
      <View style={[styles.addRow, { marginBottom: spacing.lg }]}>
        <TextInput
          style={[styles.addInput, { fontSize: fontSize.body }]}
          placeholder="New category name"
          placeholderTextColor={colors.gray[400]}
          value={newName}
          onChangeText={setNewName}
        />
        <TouchableOpacity
          style={[styles.addBtn, saving && { opacity: 0.5 }]}
          onPress={handleCreate}
          disabled={saving || !newName.trim()}
        >
          <Ionicons name="add" size={22} color={colors.white} />
        </TouchableOpacity>
      </View>

      {categories.length > 0 ? (
        categories.map((cat, index) => (
          <AnimatedCard key={cat.id} delay={index * 50} style={{ marginBottom: spacing.sm }}>
            {editTarget?.id === cat.id ? (
              <View style={[styles.editRow, { gap: spacing.sm }]}>
                <TextInput
                  style={[styles.editInput, { fontSize: fontSize.body }]}
                  value={editName}
                  onChangeText={setEditName}
                  autoFocus
                />
                <TouchableOpacity style={[styles.iconBtn, { backgroundColor: colors.success[50] }]} onPress={handleUpdate}>
                  <Ionicons name="checkmark" size={18} color={colors.success[600]} />
                </TouchableOpacity>
                <TouchableOpacity style={[styles.iconBtn, { backgroundColor: colors.gray[100] }]} onPress={() => setEditTarget(null)}>
                  <Ionicons name="close" size={18} color={colors.gray[500]} />
                </TouchableOpacity>
              </View>
            ) : (
              <View style={[styles.row, { gap: spacing.md }]}>
                <View style={[styles.iconContainer, { backgroundColor: colors.primary[50] }]}>
                  <Ionicons name="folder-outline" size={20} color={colors.primary[600]} />
                </View>
                <Text style={[styles.name, { fontSize: fontSize.body, flex: 1 }]}>{cat.name}</Text>
                <TouchableOpacity onPress={() => { setEditTarget(cat); setEditName(cat.name); }}>
                  <Ionicons name="create-outline" size={20} color={colors.primary[600]} />
                </TouchableOpacity>
                <TouchableOpacity onPress={() => handleDelete(cat)}>
                  <Ionicons name="trash-outline" size={20} color={colors.danger[600]} />
                </TouchableOpacity>
              </View>
            )}
          </AnimatedCard>
        ))
      ) : (
        <EmptyState icon="folder-outline" title="No categories" description="Create your first category" />
      )}
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  addRow: { flexDirection: 'row', gap: spacing.sm },
  addInput: {
    flex: 1, backgroundColor: colors.white, borderWidth: 1, borderColor: colors.gray[200],
    borderRadius: radii.md, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, color: colors.gray[900],
  },
  addBtn: {
    width: 44, height: 44, borderRadius: radii.md, backgroundColor: colors.primary[600],
    justifyContent: 'center', alignItems: 'center',
  },
  row: { flexDirection: 'row', alignItems: 'center' },
  iconContainer: {
    width: 38, height: 38, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center',
  },
  name: { fontWeight: '600', color: colors.gray[900] },
  editRow: { flexDirection: 'row', alignItems: 'center' },
  editInput: {
    flex: 1, backgroundColor: colors.white, borderWidth: 1, borderColor: colors.primary[300],
    borderRadius: radii.md, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, color: colors.gray[900],
  },
  iconBtn: {
    width: 36, height: 36, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center',
  },
});
