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

interface OrderItem {
  material_id: number | null;
  material_name: string;
  quantity: string;
  unit_price: string;
}

export default function PurchaseOrderScreen() {
  const navigation = useNavigation();
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();
  const [materials, setMaterials] = useState<Material[]>([]);
  const [items, setItems] = useState<OrderItem[]>([{ material_id: null, material_name: '', quantity: '1', unit_price: '' }]);
  const [remarks, setRemarks] = useState('');
  const [expectedDate, setExpectedDate] = useState('');
  const [loading, setLoading] = useState(false);
  const [showPicker, setShowPicker] = useState<number | null>(null);

  useEffect(() => {
    materialService.list().then(setMaterials).catch(() => {});
  }, []);

  const addItem = () => setItems([...items, { material_id: null, material_name: '', quantity: '1', unit_price: '' }]);
  const removeItem = (i: number) => setItems(items.filter((_, idx) => idx !== i));

  const selectMaterial = (index: number, mat: Material) => {
    const updated = [...items];
    updated[index] = { ...updated[index], material_id: mat.id, material_name: mat.material_name };
    setItems(updated);
    setShowPicker(null);
  };

  const updateItem = (index: number, field: keyof OrderItem, value: string) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const handleCreate = async () => {
    const validItems = items.filter(i => i.material_id && i.quantity);
    if (!validItems.length) return toast('Add at least one item', 'error');
    setLoading(true);
    try {
      await materialService.createOrder({
        expected_delivery_date: expectedDate || undefined,
        remarks: remarks || undefined,
        items: validItems.map(i => ({
          material_id: i.material_id!,
          quantity: parseInt(i.quantity) || 1,
          unit_price: i.unit_price ? parseFloat(i.unit_price) : undefined,
        })),
      });
      toast('Purchase order created', 'success');
      navigation.goBack();
    } catch (e: any) {
      toast(e.response?.data?.message || 'Failed to create order', 'error');
    } finally { setLoading(false); }
  };

  return (
    <ScreenContainer
      title="New Purchase Order"
      onBack={() => navigation.goBack()}
      scroll={true}
      contentPadding={contentPadding}
    >
      <View style={styles.section}>
        <Text style={[styles.label, { fontSize: fontSize.caption }]}>Expected Delivery Date</Text>
        <TextInput
          style={[styles.input, { fontSize: fontSize.body }]}
          placeholder="YYYY-MM-DD"
          placeholderTextColor={colors.gray[400]}
          value={expectedDate}
          onChangeText={setExpectedDate}
        />
        <Text style={[styles.label, { fontSize: fontSize.caption }]}>Remarks</Text>
        <TextInput
          style={[styles.input, { fontSize: fontSize.body }]}
          placeholder="Optional remarks"
          placeholderTextColor={colors.gray[400]}
          value={remarks}
          onChangeText={setRemarks}
        />
      </View>

      <Text style={[styles.sectionTitle, { fontSize: fontSize.body, marginBottom: spacing.md }]}>Order Items</Text>
      {items.map((item, index) => (
        <View key={index} style={[styles.itemCard, { marginBottom: spacing.sm }]}>
          <View style={styles.itemHeader}>
            <Text style={[styles.itemNum, { fontSize: fontSize.body }]}>Item {index + 1}</Text>
            {items.length > 1 && (
              <TouchableOpacity onPress={() => removeItem(index)}>
                <Ionicons name="trash-outline" size={20} color={colors.danger[600]} />
              </TouchableOpacity>
            )}
          </View>

          <TouchableOpacity style={styles.materialPicker} onPress={() => setShowPicker(index)}>
            <Text style={[styles.materialPickerText, { fontSize: fontSize.body, color: item.material_id ? colors.gray[900] : colors.gray[400] }]}>
              {item.material_name || 'Select material'}
            </Text>
            <Ionicons name="chevron-down" size={18} color={colors.gray[400]} />
          </TouchableOpacity>

          <View style={styles.qtyRow}>
            <View style={{ flex: 1 }}>
              <Text style={[styles.label, { fontSize: fontSize.caption }]}>Qty</Text>
              <TextInput
                style={[styles.input, { fontSize: fontSize.body }]}
                placeholder="1"
                placeholderTextColor={colors.gray[400]}
                value={item.quantity}
                onChangeText={(v) => updateItem(index, 'quantity', v)}
                keyboardType="numeric"
              />
            </View>
            <View style={{ flex: 1 }}>
              <Text style={[styles.label, { fontSize: fontSize.caption }]}>Unit Price</Text>
              <TextInput
                style={[styles.input, { fontSize: fontSize.body }]}
                placeholder="0.00"
                placeholderTextColor={colors.gray[400]}
                value={item.unit_price}
                onChangeText={(v) => updateItem(index, 'unit_price', v)}
                keyboardType="numeric"
              />
            </View>
          </View>
        </View>
      ))}

      <TouchableOpacity style={styles.addItemBtn} onPress={addItem}>
        <Ionicons name="add-circle-outline" size={20} color={colors.primary[600]} />
        <Text style={[styles.addItemText, { fontSize: fontSize.body }]}>Add Item</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[styles.createBtn, loading && { opacity: 0.5 }]}
        onPress={handleCreate}
        disabled={loading}
      >
        <Text style={[styles.createBtnText, { fontSize: fontSize.body }]}>
          {loading ? 'Creating...' : 'Create Purchase Order'}
        </Text>
      </TouchableOpacity>

      {/* Material Picker Modal */}
      <Modal visible={showPicker !== null} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={[styles.modalTitle, { fontSize: fontSize.h3 }]}>Select Material</Text>
              <TouchableOpacity onPress={() => setShowPicker(null)}>
                <Ionicons name="close" size={24} color={colors.gray[600]} />
              </TouchableOpacity>
            </View>
            <FlatList
              data={materials}
              keyExtractor={(m) => m.id.toString()}
              renderItem={({ item: m }) => (
                <TouchableOpacity
                  style={styles.materialOption}
                  onPress={() => showPicker !== null && selectMaterial(showPicker, m)}
                >
                  <View style={[styles.matIcon, { backgroundColor: colors.primary[50] }]}>
                    <Ionicons name="cube-outline" size={18} color={colors.primary[600]} />
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={[styles.matName, { fontSize: fontSize.body }]}>{m.material_name}</Text>
                    <Text style={[styles.matCode, { color: colors.gray[500], fontSize: fontSize.caption }]}>{m.material_code}</Text>
                  </View>
                  {m.category_name && (
                    <Text style={[styles.matCat, { color: colors.gray[400], fontSize: fontSize.caption }]}>{m.category_name}</Text>
                  )}
                </TouchableOpacity>
              )}
            />
          </View>
        </View>
      </Modal>
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  section: { marginBottom: spacing.lg },
  sectionTitle: { fontWeight: '600', color: colors.gray[900] },
  label: { fontWeight: '600', color: colors.gray[700], marginBottom: spacing.xs, marginTop: spacing.sm },
  input: {
    backgroundColor: colors.gray[50], borderRadius: radii.md, paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm, borderWidth: 1, borderColor: colors.gray[200], color: colors.gray[900],
  },
  itemCard: { backgroundColor: colors.white, borderRadius: radii.lg, padding: spacing.md, borderWidth: 1, borderColor: colors.gray[100] },
  itemHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: spacing.sm },
  itemNum: { fontWeight: '600', color: colors.primary[600] },
  materialPicker: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    backgroundColor: colors.gray[50], borderWidth: 1, borderColor: colors.gray[200],
    borderRadius: radii.md, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, marginBottom: spacing.sm,
  },
  materialPickerText: { fontWeight: '400' },
  qtyRow: { flexDirection: 'row', gap: spacing.sm },
  addItemBtn: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.sm,
    paddingVertical: spacing.lg, marginBottom: spacing.lg,
  },
  addItemText: { color: colors.primary[600], fontWeight: '500' },
  createBtn: {
    backgroundColor: colors.primary[600], borderRadius: radii.lg, paddingVertical: spacing.lg, alignItems: 'center',
    marginBottom: spacing.xxl,
  },
  createBtnText: { color: colors.white, fontWeight: '600' },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'flex-end' },
  modalContent: { backgroundColor: colors.white, borderTopLeftRadius: radii.xl, borderTopRightRadius: radii.xl, maxHeight: '70%' },
  modalHeader: {
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
    padding: spacing.lg, borderBottomWidth: 1, borderBottomColor: colors.border,
  },
  modalTitle: { fontWeight: '700', color: colors.gray[900] },
  materialOption: {
    flexDirection: 'row', alignItems: 'center', gap: spacing.md,
    paddingHorizontal: spacing.lg, paddingVertical: spacing.md,
    borderBottomWidth: 1, borderBottomColor: colors.gray[100],
  },
  matIcon: { width: 36, height: 36, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center' },
  matName: { fontWeight: '600', color: colors.gray[900] },
  matCode: { fontWeight: '500' },
  matCat: { fontWeight: '500' },
});
