import React, { useEffect, useState } from 'react';
import {
  View, Text, FlatList, TouchableOpacity, StyleSheet,
  Alert, ActivityIndicator, TextInput, Modal, ScrollView,
} from 'react-native';
import {
  adminFetchProducts, adminAddProduct,
  adminUpdateProduct, adminDeleteProduct,
} from '../../services/api';
import { Product } from '../../types';

const EMPTY_FORM = { name: '', description: '', price: '', category: 'lpg', image: '', stock: '0' };

export default function AddProductScreen() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading]   = useState(true);
  const [modal, setModal]       = useState(false);
  const [editing, setEditing]   = useState<Product | null>(null);
  const [form, setForm]         = useState({ ...EMPTY_FORM });
  const [saving, setSaving]     = useState(false);

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

  const loadProducts = async () => {
    setLoading(true);
    try { setProducts(await adminFetchProducts()); }
    catch { Alert.alert('Error', 'Could not load products.'); }
    finally { setLoading(false); }
  };

  const openAdd = () => { setEditing(null); setForm({ ...EMPTY_FORM }); setModal(true); };

  const openEdit = (p: Product) => {
    setEditing(p);
    setForm({
      name: p.name, description: p.description || '',
      price: String(p.price), category: p.category,
      image: p.image || '', stock: String(p.stock),
    });
    setModal(true);
  };

  const handleSave = async () => {
    if (!form.name.trim() || !form.price || Number(form.price) <= 0) {
      Alert.alert('Error', 'Name and valid price are required.');
      return;
    }
    setSaving(true);
    try {
      const payload = {
        name: form.name.trim(),
        description: form.description.trim() || undefined,
        price: parseFloat(form.price),
        category: form.category,
        image: form.image.trim() || undefined,
        stock: parseInt(form.stock) || 0,
        isActive: 1,
      };
      if (editing) {
        await adminUpdateProduct({ id: editing.id, ...payload });
      } else {
        await adminAddProduct(payload);
      }
      setModal(false);
      await loadProducts();
    } catch (err: any) {
      Alert.alert('Error', err?.response?.data?.error || 'Save failed.');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = (p: Product) => {
    Alert.alert('Delete Product', `Delete "${p.name}"?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete', style: 'destructive', onPress: async () => {
          try { await adminDeleteProduct(p.id); await loadProducts(); }
          catch { Alert.alert('Error', 'Could not delete product.'); }
        },
      },
    ]);
  };

  const renderItem = ({ item }: { item: Product }) => (
    <View style={styles.card}>
      <View style={styles.cardTop}>
        <Text style={styles.cardName}>{item.name}</Text>
        <Text style={styles.cardCategory}>{item.category}</Text>
      </View>
      <Text style={styles.cardPrice}>₦{Number(item.price).toLocaleString()}</Text>
      <Text style={styles.cardStock}>Stock: {item.stock} | {item.is_active ? '✅ Active' : '❌ Inactive'}</Text>
      <View style={styles.actions}>
        <TouchableOpacity style={styles.editBtn} onPress={() => openEdit(item)}>
          <Text style={styles.editBtnText}>✏️ Edit</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.delBtn} onPress={() => handleDelete(item)}>
          <Text style={styles.delBtnText}>🗑️ Delete</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <View style={styles.bg}>
      <View style={styles.header}>
        <Text style={styles.title}>📦 Products</Text>
        <TouchableOpacity style={styles.addBtn} onPress={openAdd}>
          <Text style={styles.addBtnText}>+ Add</Text>
        </TouchableOpacity>
      </View>

      {loading
        ? <ActivityIndicator color="#f97316" size="large" style={{ marginTop: 40 }} />
        : (
          <FlatList
            data={products}
            keyExtractor={(i: Product) => i.id}
            renderItem={renderItem}
            contentContainerStyle={styles.list}
            ListEmptyComponent={<Text style={styles.empty}>No products yet.</Text>}
          />
        )
      }

      {/* Add / Edit Modal */}
      <Modal visible={modal} animationType="slide" onRequestClose={() => setModal(false)}>
        <ScrollView style={styles.modal} contentContainerStyle={styles.modalContent}>
          <Text style={styles.modalTitle}>{editing ? 'Edit Product' : 'Add New Product'}</Text>

          {(['name', 'description', 'price', 'image'] as const).map(field => (
            <View key={field}>
              <Text style={styles.label}>{field.charAt(0).toUpperCase() + field.slice(1)}{field === 'name' || field === 'price' ? ' *' : ''}</Text>
              <TextInput
                style={styles.input}
                value={form[field]}
                onChangeText={v => setForm(f => ({ ...f, [field]: v }))}
                placeholder={field}
                placeholderTextColor="#64748b"
                keyboardType={field === 'price' ? 'decimal-pad' : 'default'}
              />
            </View>
          ))}

          <Text style={styles.label}>Category</Text>
          <View style={styles.catRow}>
            {['lpg', 'accessory'].map(cat => (
              <TouchableOpacity
                key={cat}
                style={[styles.catBtn, form.category === cat && styles.catActive]}
                onPress={() => setForm(f => ({ ...f, category: cat }))}
              >
                <Text style={[styles.catText, form.category === cat && styles.catTextActive]}>
                  {cat === 'lpg' ? '🔥 LPG' : '🔧 Accessory'}
                </Text>
              </TouchableOpacity>
            ))}
          </View>

          <Text style={styles.label}>Stock</Text>
          <TextInput
            style={styles.input}
            value={form.stock}
            onChangeText={v => setForm(f => ({ ...f, stock: v }))}
            placeholder="0"
            placeholderTextColor="#64748b"
            keyboardType="number-pad"
          />

          <View style={styles.modalBtns}>
            <TouchableOpacity style={styles.cancelBtn} onPress={() => setModal(false)}>
              <Text style={styles.cancelText}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.saveBtn} onPress={handleSave} disabled={saving}>
              {saving ? <ActivityIndicator color="#fff" /> : <Text style={styles.saveBtnText}>Save</Text>}
            </TouchableOpacity>
          </View>
        </ScrollView>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  bg:             { flex: 1, backgroundColor: '#0f172a' },
  header:         { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 },
  title:          { fontSize: 20, fontWeight: '700', color: '#fff' },
  addBtn:         { backgroundColor: '#f97316', borderRadius: 8, paddingHorizontal: 14, paddingVertical: 8 },
  addBtnText:     { color: '#fff', fontWeight: '700' },
  list:           { padding: 16, paddingTop: 0 },
  card:           { backgroundColor: '#1e293b', borderRadius: 14, padding: 16, marginBottom: 12 },
  cardTop:        { flexDirection: 'row', justifyContent: 'space-between' },
  cardName:       { color: '#fff', fontWeight: '700', fontSize: 16, flex: 1 },
  cardCategory:   { color: '#f97316', fontSize: 12, fontWeight: '700' },
  cardPrice:      { color: '#f97316', fontWeight: '800', fontSize: 17, marginVertical: 4 },
  cardStock:      { color: '#64748b', fontSize: 12, marginBottom: 10 },
  actions:        { flexDirection: 'row', gap: 10 },
  editBtn:        { backgroundColor: '#334155', borderRadius: 8, paddingHorizontal: 12, paddingVertical: 6 },
  editBtnText:    { color: '#fff', fontWeight: '600' },
  delBtn:         { backgroundColor: 'rgba(239,68,68,0.15)', borderRadius: 8, paddingHorizontal: 12, paddingVertical: 6 },
  delBtnText:     { color: '#ef4444', fontWeight: '600' },
  empty:          { color: '#64748b', textAlign: 'center', marginTop: 40 },
  modal:          { flex: 1, backgroundColor: '#0f172a' },
  modalContent:   { padding: 24 },
  modalTitle:     { fontSize: 22, fontWeight: '800', color: '#fff', marginBottom: 20 },
  label:          { color: '#94a3b8', fontSize: 13, marginBottom: 6 },
  input:          { backgroundColor: '#1e293b', borderRadius: 10, padding: 14, color: '#fff', marginBottom: 14, fontSize: 14, borderWidth: 1, borderColor: '#334155' },
  catRow:         { flexDirection: 'row', gap: 10, marginBottom: 14 },
  catBtn:         { flex: 1, backgroundColor: '#1e293b', borderRadius: 10, padding: 12, alignItems: 'center', borderWidth: 1, borderColor: '#334155' },
  catActive:      { borderColor: '#f97316', backgroundColor: 'rgba(249,115,22,0.1)' },
  catText:        { color: '#94a3b8', fontWeight: '600' },
  catTextActive:  { color: '#f97316' },
  modalBtns:      { flexDirection: 'row', gap: 12, marginTop: 8 },
  cancelBtn:      { flex: 1, backgroundColor: '#1e293b', borderRadius: 10, padding: 14, alignItems: 'center' },
  cancelText:     { color: '#94a3b8', fontWeight: '700' },
  saveBtn:        { flex: 1, backgroundColor: '#f97316', borderRadius: 10, padding: 14, alignItems: 'center' },
  saveBtnText:    { color: '#fff', fontWeight: '700' },
});
