import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, RefreshControl } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { StatusBadge } from '../../components/common/StatusBadge';
import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
import { useResponsive } from '../../hooks/useResponsive';
import { useToast } from '../../context/ToastContext';
import { useAuth } from '../../hooks/useAuth';
import { materialService } from '../../services/materialService';
import { Material, MaterialRequest, MaterialOrder } from '../../types';
import { colors, spacing, radii } from '../../theme';

type TabKey = 'MATERIALS' | 'TRACKING' | 'ORDERS';

const CATEGORY_ICONS: Record<string, keyof typeof Ionicons.glyphMap> = {
  'Electrical': 'flash-outline', 'Hardware': 'hammer-outline',
  'Safety': 'shield-checkmark-outline', 'General': 'cube-outline',
};
function getCategoryIcon(name?: string): keyof typeof Ionicons.glyphMap {
  if (!name) return 'cube-outline';
  const key = Object.keys(CATEGORY_ICONS).find(k => name.toLowerCase().includes(k.toLowerCase()));
  return key ? CATEGORY_ICONS[key] : 'cube-outline';
}

export default function MaterialListScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();
  const { hasPermission } = useAuth();
  const [activeTab, setActiveTab] = useState<TabKey>('MATERIALS');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [search, setSearch] = useState('');
  const [deleteTarget, setDeleteTarget] = useState<Material | null>(null);
  const [deleting, setDeleting] = useState(false);

  const [materials, setMaterials] = useState<Material[]>([]);
  const [tracking, setTracking] = useState<MaterialRequest[]>([]);
  const [orders, setOrders] = useState<MaterialOrder[]>([]);

  const loadData = async () => {
    try {
      const [m, t, o] = await Promise.all([
        materialService.list().catch(() => []),
        materialService.listAll().catch(() => []),
        materialService.listOrders().catch(() => []),
      ]);
      setMaterials(m);
      setTracking(t);
      setOrders(o);
    } catch {} finally { setLoading(false); setRefreshing(false); }
  };

  useFocusEffect(useCallback(() => { loadData(); }, []));
  const onRefresh = () => { setRefreshing(true); loadData(); };

  const handleDeleteMaterial = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    try {
      await materialService.remove(deleteTarget.id);
      toast('Material deleted', 'success');
      setDeleteTarget(null);
      loadData();
    } catch (e: any) {
      toast(e.response?.data?.message || 'Failed to delete material', 'error');
    } finally {
      setDeleting(false);
    }
  };

  const filteredMaterials = materials.filter(m =>
    !search || m.material_name.toLowerCase().includes(search.toLowerCase()) || (m.material_code || '').toLowerCase().includes(search.toLowerCase())
  );
  const filteredTracking = tracking.filter(t =>
    !search || (t.material_name || '').toLowerCase().includes(search.toLowerCase()) || (t.job_number || '').toLowerCase().includes(search.toLowerCase())
  );

  const tabCounts = { MATERIALS: materials.length, TRACKING: tracking.length, ORDERS: orders.length };

  const toolbar = (
    <View style={{ paddingHorizontal: contentPadding, paddingBottom: spacing.md }}>
      <View style={styles.searchInput}>
        <Ionicons name="search" size={18} color={colors.gray[400]} />
        <TextInput
          style={[styles.searchField, { paddingVertical: spacing.md, fontSize: fontSize.body }]}
          placeholder={activeTab === 'MATERIALS' ? 'Search materials...' : 'Search tracking...'}
          placeholderTextColor={colors.gray[400]}
          value={search}
          onChangeText={setSearch}
        />
        {search.length > 0 && <Ionicons name="close-circle" size={18} color={colors.gray[400]} onPress={() => setSearch('')} />}
      </View>

      <View style={styles.tabRow}>
        {([
          { key: 'MATERIALS' as TabKey, label: 'Materials', icon: 'cube-outline' },
          { key: 'TRACKING' as TabKey, label: 'Tracking', icon: 'git-network-outline' },
          { key: 'ORDERS' as TabKey, label: 'Orders', icon: 'receipt-outline' },
        ]).map(tab => {
          const isActive = activeTab === tab.key;
          return (
            <TouchableOpacity key={tab.key} style={[styles.tab, isActive && styles.tabActive]} onPress={() => { setActiveTab(tab.key); setSearch(''); }}>
              <Ionicons name={tab.icon as any} size={16} color={isActive ? colors.white : colors.gray[500]} />
              <Text style={[styles.tabText, { fontSize: fontSize.caption }, isActive && styles.tabTextActive]}>{tab.label}</Text>
              <View style={[styles.tabBadge, { backgroundColor: isActive ? 'rgba(255,255,255,0.3)' : colors.gray[200] }]}>
                <Text style={[styles.tabBadgeText, { color: isActive ? colors.white : colors.gray[500], fontSize: 10 }]}>{tabCounts[tab.key]}</Text>
              </View>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );

  return (
    <>
    <ScreenContainer
      title="Materials"
      subtitle={`${materials.length} items`}
      onBack={() => navigation.goBack()}
      loading={loading}
      refreshing={refreshing}
      onRefresh={onRefresh}
      scroll={true}
      contentPadding={contentPadding}
      rightAction={{
        icon: activeTab === 'ORDERS' ? 'receipt-outline' : 'add-circle-outline',
        onPress: () => navigation.navigate(activeTab === 'ORDERS' ? 'PurchaseOrder' : 'MaterialCreate'),
      }}
    >
      {toolbar}

      {/* MATERIALS TAB */}
      {activeTab === 'MATERIALS' && (
        <>
          <View style={[styles.quickActions, { paddingHorizontal: contentPadding, marginBottom: spacing.md }]}>
            <TouchableOpacity style={styles.quickBtn} onPress={() => navigation.navigate('CategoryManage')}>
              <Ionicons name="folder-outline" size={18} color={colors.primary[600]} />
              <Text style={[styles.quickBtnText, { fontSize: fontSize.caption, color: colors.primary[600] }]}>Categories</Text>
            </TouchableOpacity>
          </View>
          {filteredMaterials.length > 0 ? filteredMaterials.map((mat, index) => (
            <AnimatedCard key={mat.id} delay={index * 40} style={{ marginBottom: spacing.sm }}>
              <View style={[styles.card, { gap: spacing.md }]}>
                <TouchableOpacity style={{ flex: 1, flexDirection: 'row', gap: spacing.md }} onPress={() => navigation.navigate('MaterialDetail', { materialId: mat.id, material: mat })} activeOpacity={0.7}>
                  <View style={[styles.iconContainer, { backgroundColor: colors.primary[50] }]}>
                    <Ionicons name={getCategoryIcon(mat.category_name)} size={22} color={colors.primary[600]} />
                  </View>
                  <View style={styles.info}>
                    <Text style={[styles.name, { fontSize: fontSize.body }]} numberOfLines={1}>{mat.material_name}</Text>
                    <View style={styles.metaRow}>
                      <StatusBadge status={mat.status} />
                      <Text style={[styles.code, { color: colors.gray[500], fontSize: fontSize.caption }]}>{mat.material_code}</Text>
                    </View>
                    <View style={styles.metaRow}>
                      {mat.category_name && <Text style={[styles.cat, { color: colors.gray[400], fontSize: fontSize.caption }]}>{mat.category_name}{mat.unit_name ? ` • ${mat.unit_name}` : ''}</Text>}
                      <Text style={[styles.code, { color: (mat.stock_quantity || 0) > 0 ? colors.success[600] : colors.gray[400], fontSize: fontSize.caption }]}>
                        Stock: {mat.stock_quantity ?? 0}
                      </Text>
                    </View>
                  </View>
                  <Ionicons name="chevron-forward" size={16} color={colors.gray[300]} />
                </TouchableOpacity>
                {hasPermission('material.order') && (
                  <TouchableOpacity
                    style={[styles.deleteBtn, { backgroundColor: colors.danger?.[50] || '#fef2f2' }]}
                    onPress={() => setDeleteTarget(mat)}
                  >
                    <Ionicons name="trash-outline" size={14} color={colors.danger?.[600] || 'red'} />
                  </TouchableOpacity>
                )}
              </View>
            </AnimatedCard>
          )) : <EmptyState icon="cube-outline" title="No materials" description="Create your first material" />}
        </>
      )}

      {/* TRACKING TAB */}
      {activeTab === 'TRACKING' && (
        <>
          {filteredTracking.length > 0 ? filteredTracking.map((item, index) => {
            const isAssigned = item.material_status === 'IN_USE';
            const isReturned = item.material_status === 'RETURNED';
            const personName = item.assigned_to_name ? `${item.assigned_to_name} ${item.assigned_to_last || ''}` : null;
            return (
              <AnimatedCard key={item.id} delay={index * 40} style={{ marginBottom: spacing.sm }}>
                <View style={[styles.card, { gap: spacing.md }]}>
                  <View style={[styles.iconContainer, { backgroundColor: isReturned ? colors.success[50] : isAssigned ? colors.warning[50] : colors.primary[50] }]}>
                    <Ionicons name={getCategoryIcon(item.category_name)} size={22} color={isReturned ? colors.success[600] : isAssigned ? colors.warning[600] : colors.primary[600]} />
                  </View>
                  <View style={styles.info}>
                    <Text style={[styles.name, { fontSize: fontSize.body }]} numberOfLines={1}>{item.material_name}</Text>
                    {item.job_number && <Text style={[styles.code, { color: colors.gray[500], fontSize: fontSize.caption }]}>{item.job_number}</Text>}
                    <View style={styles.metaRow}>
                      <StatusBadge status={item.material_status || 'STOCK'} />
                      {item.approved_quantity > 0 && <Text style={[styles.code, { fontSize: fontSize.caption }]}>x{item.approved_quantity}</Text>}
                    </View>
                    {personName && <Text style={[styles.cat, { color: colors.warning[600], fontSize: fontSize.caption }]}>{personName}</Text>}
                  </View>
                </View>
              </AnimatedCard>
            );
          }) : <EmptyState icon="git-network-outline" title="No tracking" description="Request materials from jobs" />}
        </>
      )}

      {/* ORDERS TAB */}
      {activeTab === 'ORDERS' && (
        <>
          {orders.length > 0 ? orders.map((order, index) => (
            <AnimatedCard key={order.id} delay={index * 40} style={{ marginBottom: spacing.sm }}>
              <TouchableOpacity style={[styles.card, { gap: spacing.md }]} onPress={() => navigation.navigate('OrderDetail', { orderId: order.id })} activeOpacity={0.7}>
                <View style={[styles.iconContainer, { backgroundColor: colors.info[50] }]}>
                  <Ionicons name="receipt-outline" size={22} color={colors.info[600]} />
                </View>
                <View style={styles.info}>
                  <Text style={[styles.name, { fontSize: fontSize.body }]}>{order.order_number}</Text>
                  <View style={styles.metaRow}>
                    <StatusBadge status={order.order_status || 'REQUESTED'} />
                    <Text style={[styles.code, { color: colors.gray[500], fontSize: fontSize.caption }]}>{new Date(order.order_date).toLocaleDateString()}</Text>
                  </View>
                </View>
                <Ionicons name="chevron-forward" size={16} color={colors.gray[300]} />
              </TouchableOpacity>
            </AnimatedCard>
          )) : <EmptyState icon="receipt-outline" title="No orders" description="Create a purchase order" />}
        </>
      )}
    </ScreenContainer>
    <ConfirmDialog
      visible={!!deleteTarget}
      title="Delete Material"
      message={`Are you sure you want to delete "${deleteTarget?.material_name}"? This cannot be undone.`}
      confirmLabel={deleting ? 'Deleting...' : 'Delete'}
      cancelLabel="Cancel"
      onConfirm={handleDeleteMaterial}
      onCancel={() => setDeleteTarget(null)}
    />
    </>
  );
}

const styles = StyleSheet.create({
  searchInput: { flexDirection: 'row', alignItems: 'center', backgroundColor: colors.white, borderRadius: radii.md, borderWidth: 1, borderColor: colors.gray[200], paddingHorizontal: spacing.md, gap: spacing.sm, marginBottom: spacing.md },
  searchField: { flex: 1, color: colors.gray[900] },
  tabRow: { flexDirection: 'row', gap: spacing.xs },
  tab: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4, paddingVertical: spacing.sm, borderRadius: radii.md, backgroundColor: colors.white, borderWidth: 1, borderColor: colors.gray[200] },
  tabActive: { backgroundColor: colors.primary[600], borderColor: colors.primary[600] },
  tabText: { fontWeight: '600', color: colors.gray[500] },
  tabTextActive: { color: colors.white },
  tabBadge: { paddingHorizontal: 5, paddingVertical: 1, borderRadius: 8, minWidth: 18, alignItems: 'center' },
  tabBadgeText: { fontWeight: '700' },
  quickActions: { flexDirection: 'row', gap: spacing.sm },
  quickBtn: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, borderRadius: radii.md, borderWidth: 1, borderColor: colors.primary[200], backgroundColor: colors.primary[50] },
  quickBtnText: { fontWeight: '600' },
  card: { flexDirection: 'row', alignItems: 'center' },
  iconContainer: { width: 44, height: 44, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' },
  info: { flex: 1, gap: 2 },
  name: { fontWeight: '600', color: colors.gray[900] },
  metaRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  code: { fontWeight: '500', color: colors.gray[500] },
  cat: { fontWeight: '500' },
  deleteBtn: { paddingHorizontal: spacing.sm, paddingVertical: spacing.xs, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center' },
});
