import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Modal, FlatList } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
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 { adminService } from '../../services/adminService';
import { Material, MaterialRequest, User } from '../../types';
import { colors, spacing, radii } from '../../theme';

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 MaterialDetailScreen() {
  const navigation = useNavigation<any>();
  const route = useRoute<any>();
  const { materialId } = route.params;
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();
  const { hasPermission } = useAuth();

  const [material, setMaterial] = useState<Material | null>(null);
  const [tracking, setTracking] = useState<MaterialRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [assigning, setAssigning] = useState(false);
  const [returnTarget, setReturnTarget] = useState<MaterialRequest | null>(null);
  const [returning, setReturning] = useState(false);

  const loadData = async () => {
    try {
      const [matData, trackData] = await Promise.all([
        materialService.getById(materialId).catch(() => null),
        materialService.listAll().then(list => list.filter(t => t.material_id === materialId)).catch(() => []),
      ]);
      if (matData) setMaterial(matData);
      setTracking(trackData);
    } catch {
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const onRefresh = () => { setRefreshing(true); loadData(); };

  const loadUsers = async () => {
    try {
      const data = await adminService.users();
      setUsers(data);
    } catch {}
  };

  const handleAssign = async (userId: number) => {
    if (!returnTarget) return;
    setAssigning(true);
    try {
      await materialService.approve(returnTarget.id);
      await materialService.assignToPerson(returnTarget.id, userId);
      toast('Material assigned', 'success');
      setShowAssignModal(false);
      setReturnTarget(null);
      loadData();
    } catch {
      toast('Failed to assign', 'error');
    } finally {
      setAssigning(false);
    }
  };

  const handleReturn = async (item: MaterialRequest) => {
    setReturning(true);
    try {
      await materialService.returnToStock(item.id);
      toast('Material returned to stock', 'success');
      setReturnTarget(null);
      loadData();
    } catch {
      toast('Failed to return', 'error');
    } finally {
      setReturning(false);
    }
  };

  const openAssign = async (item: MaterialRequest) => {
    await loadUsers();
    setReturnTarget(item);
    setShowAssignModal(true);
  };

  const icon = getCategoryIcon(material?.category_name);

  return (
    <>
      <ScreenContainer
        title={material?.material_name || 'Material Detail'}
        subtitle={material?.material_code || `#${materialId}`}
        onBack={() => navigation.goBack()}
        rightAction={undefined}
        loading={loading}
        refreshing={refreshing}
        onRefresh={onRefresh}
        scroll={true}
        contentPadding={contentPadding}
      >
        {/* Header Card */}
        <AnimatedCard delay={0}>
          <View style={styles.headerSection}>
            <View style={[styles.iconLarge, { backgroundColor: colors.primary[50] }]}>
              <Ionicons name={icon} size={32} color={colors.primary[600]} />
            </View>
            <View style={styles.headerInfo}>
              <Text style={[styles.title, { fontSize: fontSize.h3 }]}>{material?.material_name}</Text>
              <Text style={[styles.subtitle, { color: colors.gray[500], fontSize: fontSize.caption }]}>
                {material?.category_name || 'No category'}{material?.unit_name ? ` • ${material.unit_name}` : ''}
              </Text>
            </View>
            {material?.status && (
              <StatusBadge status={material.status} size="md" />
            )}
          </View>
        </AnimatedCard>

        {/* Material Info Card */}
        <AnimatedCard delay={100} style={{ marginTop: spacing.md }}>
          <Text style={[styles.sectionTitle, { fontSize: fontSize.body, marginBottom: spacing.md }]}>Material Info</Text>
          <View style={styles.detailGrid}>
            <DetailRow icon="pricetag-outline" label="Code" value={material?.material_code || '-'} fontSize={fontSize} />
            <DetailRow icon="cube-outline" label="Category" value={material?.category_name || '-'} fontSize={fontSize} />
            <DetailRow icon="resize-outline" label="Unit" value={material?.unit_name || '-'} fontSize={fontSize} />
            <DetailRow
              icon="layers-outline"
              label="Stock Quantity"
              value={`${material?.stock_quantity ?? 0}`}
              fontSize={fontSize}
              highlight={(material?.stock_quantity ?? 0) > 0}
              highlightColor={colors.success[600]}
            />
            {material?.description && <DetailRow icon="document-text-outline" label="Description" value={material.description} fontSize={fontSize} />}
          </View>
        </AnimatedCard>

        {/* Tracking / Job Requests Card */}
        <AnimatedCard delay={200} style={{ marginTop: spacing.md }}>
          <View style={styles.sectionHeader}>
            <Text style={[styles.sectionTitle, { fontSize: fontSize.body }]}>Job Requests ({tracking.length})</Text>
          </View>
          {tracking.length > 0 ? tracking.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 (
              <View key={item.id} style={[styles.trackingRow, { borderTopWidth: index > 0 ? 1 : 0, borderTopColor: colors.gray[100], paddingTop: spacing.md, marginTop: index > 0 ? spacing.md : 0 }]}>
                <View style={[styles.trackingIcon, { backgroundColor: isReturned ? colors.success[50] : isAssigned ? colors.warning[50] : colors.primary[50] }]}>
                  <Ionicons name={isReturned ? 'checkmark-circle-outline' : isAssigned ? 'person-outline' : 'time-outline'} size={18} color={isReturned ? colors.success[600] : isAssigned ? colors.warning[600] : colors.primary[600]} />
                </View>
                <View style={styles.trackingInfo}>
                  <Text style={[styles.trackingJob, { fontSize: fontSize.body }]}>{item.job_number || 'N/A'} - {item.job_title || ''}</Text>
                  <View style={styles.trackingMeta}>
                    <StatusBadge status={item.material_status || 'STOCK'} size="sm" />
                    <Text style={[styles.trackingQty, { fontSize: fontSize.caption }]}>
                      Qty: {item.approved_quantity || item.requested_quantity || 0}
                    </Text>
                  </View>
                  {personName && (
                    <Text style={[styles.trackingPerson, { color: colors.warning[600], fontSize: fontSize.caption }]}>
                      Assigned: {personName}
                    </Text>
                  )}
                </View>
                <View style={styles.trackingActions}>
                  {item.material_status === 'STOCK' && item.status === 'REQUESTED' && hasPermission('material.approve') && (
                    <TouchableOpacity
                      style={[styles.actionBtn, { backgroundColor: colors.primary[50] }]}
                      onPress={() => openAssign(item)}
                    >
                      <Ionicons name="person-add-outline" size={16} color={colors.primary[600]} />
                    </TouchableOpacity>
                  )}
                  {isAssigned && (
                    <TouchableOpacity
                      style={[styles.actionBtn, { backgroundColor: colors.success[50] }]}
                      onPress={() => handleReturn(item)}
                    >
                      <Ionicons name="return-down-back-outline" size={16} color={colors.success[600]} />
                    </TouchableOpacity>
                  )}
                </View>
              </View>
            );
          }) : (
            <View style={styles.emptyContainer}>
              <Ionicons name="git-network-outline" size={32} color={colors.gray[300]} />
              <Text style={[styles.emptyText, { fontSize: fontSize.body }]}>No job requests yet</Text>
            </View>
          )}
        </AnimatedCard>

        <View style={{ height: 40 }} />
      </ScreenContainer>

      {/* Assign Modal */}
      <Modal visible={showAssignModal} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={[styles.modalTitle, { fontSize: fontSize.h3 }]}>Assign to Person</Text>
              <TouchableOpacity onPress={() => { setShowAssignModal(false); setReturnTarget(null); }}>
                <Ionicons name="close" size={24} color={colors.gray[600]} />
              </TouchableOpacity>
            </View>
            {users.length > 0 ? (
              <FlatList
                data={users}
                keyExtractor={(u) => u.id.toString()}
                renderItem={({ item: u }) => (
                  <TouchableOpacity
                    style={[styles.userOption, { paddingVertical: 12, paddingHorizontal: spacing.lg }]}
                    onPress={() => handleAssign(u.id)}
                    disabled={assigning}
                  >
                    <View style={[styles.userAvatar, { backgroundColor: colors.primary[100] }]}>
                      <Text style={[styles.userAvatarText, { color: colors.primary[700] }]}>
                        {u.first_name[0]}{u.last_name?.[0] || ''}
                      </Text>
                    </View>
                    <View style={styles.userInfo}>
                      <Text style={[styles.userName, { fontSize: fontSize.body }]}>{u.first_name} {u.last_name}</Text>
                      <Text style={[styles.userEmail, { fontSize: fontSize.caption }]}>{u.email}</Text>
                    </View>
                    <Ionicons name="add-circle-outline" size={22} color={colors.primary[600]} />
                  </TouchableOpacity>
                )}
              />
            ) : (
              <Text style={[styles.emptyText, { padding: spacing.xl }]}>No users available</Text>
            )}
          </View>
        </View>
      </Modal>

      <ConfirmDialog
        visible={!!returnTarget}
        title="Return to Stock"
        message={`Return "${returnTarget?.material_name}" to stock? This marks it as available for other jobs.`}
        confirmLabel="Return"
        cancelLabel="Cancel"
        onConfirm={() => returnTarget && handleReturn(returnTarget)}
        onCancel={() => setReturnTarget(null)}
      />
    </>
  );
}

function DetailRow({ icon, label, value, fontSize, highlight, highlightColor }: {
  icon: keyof typeof Ionicons.glyphMap;
  label: string;
  value: string;
  fontSize: any;
  highlight?: boolean;
  highlightColor?: string;
}) {
  return (
    <View style={[detailStyles.row, { paddingVertical: spacing.sm, borderBottomWidth: 1, borderBottomColor: colors.gray[100] }]}>
      <View style={detailStyles.label}>
        <Ionicons name={icon} size={14} color={colors.gray[400]} />
        <Text style={[detailStyles.labelText, { color: colors.gray[500], fontSize: fontSize.caption }]}>{label}</Text>
      </View>
      <Text style={[detailStyles.value, { color: highlight ? (highlightColor || colors.primary[600]) : colors.gray[800], fontSize: fontSize.body, fontWeight: highlight ? '700' : '400' }]} numberOfLines={2}>
        {value}
      </Text>
    </View>
  );
}

const detailStyles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  label: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
  },
  labelText: {
    fontWeight: '500',
  },
  value: {
    flex: 1,
    textAlign: 'right',
  },
});

const styles = StyleSheet.create({
  headerSection: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  iconLarge: {
    width: 56,
    height: 56,
    borderRadius: radii.xl,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerInfo: {
    flex: 1,
  },
  title: {
    fontWeight: '700',
    color: colors.gray[900],
  },
  subtitle: {
    marginTop: 2,
  },
  sectionTitle: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  detailGrid: {},
  trackingRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: spacing.md,
  },
  trackingIcon: {
    width: 36,
    height: 36,
    borderRadius: radii.md,
    justifyContent: 'center',
    alignItems: 'center',
  },
  trackingInfo: {
    flex: 1,
    gap: 4,
  },
  trackingJob: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  trackingMeta: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
  },
  trackingQty: {
    color: colors.gray[500],
    fontWeight: '500',
  },
  trackingPerson: {
    fontWeight: '500',
  },
  trackingActions: {
    flexDirection: 'row',
    gap: spacing.xs,
  },
  actionBtn: {
    width: 32,
    height: 32,
    borderRadius: radii.md,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyContainer: {
    alignItems: 'center',
    paddingVertical: spacing.xl,
    gap: spacing.sm,
  },
  emptyText: {
    color: colors.gray[400],
    textAlign: 'center',
  },
  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],
  },
  userOption: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.gray[100],
  },
  userAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  userAvatarText: {
    fontWeight: '700',
    fontSize: 14,
  },
  userInfo: {
    flex: 1,
  },
  userName: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  userEmail: {
    color: colors.gray[500],
  },
});
