import { router } from 'expo-router';
import { FlatList, Pressable, RefreshControl, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import {
  WORK_ORDER_PRIORITY_LABELS,
  WORK_ORDER_STATUS_LABELS,
  WORK_ORDER_TYPE_LABELS,
  type WorkOrderPriority,
  type WorkOrderStatus,
} from '@siop/shared';
import { useWorkOrders } from '@/api/exploitation';
import { EnteteTabs } from '@/composants/ui';
import { triJournee } from '@/lib/journee';
import { useTokens, type Tokens } from '@/theme/tokens';

/** Ordres de travail — maquette « mobile ouvert à tous les rôles », écran 4 :
 *  à la différence de « Ma journée » (Technicien, ses OT uniquement),
 *  Administrateur/Gestionnaire/Dispatcher ont `viewOther` — l'API renvoie
 *  déjà TOUS les OT (ADR-003, rien à filtrer ici). Même tri priorité puis
 *  échéance que « Ma journée » ; ouvrir un OT réutilise la fiche R4 telle
 *  quelle (elle affiche déjà les actions permises via `allowedTransitions`). */

const STYLE_STATUT: Record<WorkOrderStatus, (t: Tokens) => [string, string]> = {
  OPEN: (t) => [t.stOuvert, t.stOuvertFond],
  IN_PROGRESS: (t) => [t.stEncours, t.stEncoursFond],
  ON_HOLD: (t) => [t.stAttente, t.stAttenteFond],
  DONE: (t) => [t.stTermine, t.stTermineFond],
  CANCELLED: (t) => [t.stAnnule, t.stAnnuleFond],
};
const STRIE_PRIORITE: Record<WorkOrderPriority, (t: Tokens) => string> = {
  PERSON_TRAPPED: (t) => t.prioBloque,
  HIGH: (t) => t.prioHaute,
  MEDIUM: (t) => t.prioMoyenne,
  LOW: (t) => t.prioBasse,
  NONE: () => 'transparent',
};

export default function PageOT() {
  const t = useTokens();
  const { data: workOrders, refetch, isFetching } = useWorkOrders();
  const ots = triJournee(workOrders ?? []);
  const urgences = ots.filter((o) => o.priority === 'PERSON_TRAPPED');

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
      <View style={{ padding: 14, gap: 10, flex: 1 }}>
        <EnteteTabs />
        <View style={{ flexDirection: 'row', alignItems: 'baseline' }}>
          <Text style={{ fontFamily: 'Manrope_800ExtraBold', fontSize: 19, color: t.encre }}>
            Ordres de travail
          </Text>
          <Text style={{ marginLeft: 'auto', fontFamily: 'Manrope_600SemiBold', fontSize: 11, color: t.encre3 }}>
            {ots.length}
          </Text>
        </View>

        {urgences.length ? (
          <View
            style={{
              backgroundColor: t.prioBloqueFond,
              borderRadius: 10,
              padding: 9,
              flexDirection: 'row',
              alignItems: 'center',
              gap: 8,
            }}
          >
            <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: t.prioBloque }} />
            <Text style={{ color: t.prioBloque, fontFamily: 'Manrope_800ExtraBold', fontSize: 12 }}>
              {urgences.length === 1
                ? `1 personne bloquée — ${urgences[0]!.assetReference} · ${urgences[0]!.siteName}`
                : `${urgences.length} personnes bloquées`}
            </Text>
          </View>
        ) : null}

        <FlatList
          data={ots}
          keyExtractor={(o) => o.id}
          refreshControl={
            <RefreshControl refreshing={isFetching} onRefresh={() => void refetch()} tintColor={t.primaire} />
          }
          contentContainerStyle={{ gap: 8, paddingBottom: 12 }}
          ListEmptyComponent={
            <Text style={{ color: t.encre3, fontFamily: 'Manrope_600SemiBold', padding: 16, textAlign: 'center' }}>
              Aucun OT — tirez pour rafraîchir.
            </Text>
          }
          renderItem={({ item: o }) => {
            const [enc, fond] = STYLE_STATUT[o.status](t);
            return (
              <Pressable
                accessibilityRole="button"
                accessibilityLabel={`${o.reference} — ${o.title}`}
                onPress={() => router.push(`/ot/${o.id}`)}
                style={{
                  backgroundColor: t.surface,
                  borderColor: t.bordure,
                  borderWidth: 1,
                  borderRadius: 12,
                  borderLeftWidth: 4,
                  borderLeftColor: STRIE_PRIORITE[o.priority](t),
                  padding: 11,
                  gap: 2,
                }}
              >
                <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
                  <Text
                    style={{
                      fontFamily: 'Manrope_700Bold',
                      fontSize: 10.5,
                      letterSpacing: 0.6,
                      textTransform: 'uppercase',
                      color: t.encre2,
                      flex: 1,
                    }}
                  >
                    {o.reference} · {WORK_ORDER_TYPE_LABELS[o.type]}
                  </Text>
                  <Text
                    style={{
                      fontFamily: 'Manrope_700Bold',
                      fontSize: 10.5,
                      color: enc,
                      backgroundColor: fond,
                      paddingHorizontal: 8,
                      paddingVertical: 2,
                      borderRadius: 999,
                      overflow: 'hidden',
                    }}
                  >
                    {WORK_ORDER_STATUS_LABELS[o.status]}
                  </Text>
                </View>
                <Text style={{ fontFamily: 'Manrope_700Bold', fontSize: 14, color: t.encre }}>
                  {o.title}
                </Text>
                <Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 12, color: t.encre2 }}>
                  Asc. {o.assetReference} — {o.siteName}
                  {o.dueDate
                    ? ` · échéance ${new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'short' }).format(new Date(o.dueDate))}`
                    : ''}
                  {o.priority !== 'NONE' && o.priority !== 'PERSON_TRAPPED'
                    ? ` · ${WORK_ORDER_PRIORITY_LABELS[o.priority]}`
                    : ''}
                </Text>
              </Pressable>
            );
          }}
        />
      </View>
    </SafeAreaView>
  );
}
