import { useQuery } from '@tanstack/react-query';
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 { api, unwrap } from '@/api/client';
import { useHorsLigne } from '@/auth/session';
import { EnteteTabs } from '@/composants/ui';
import { triJournee } from '@/lib/journee';
import { useTokens, type Tokens } from '@/theme/tokens';

/** Écran 1 de la maquette R4 : les OT du technicien, priorité puis
 *  échéance, « personne bloquée » en tête. Hors-ligne : le cache persisté
 *  sert la liste, le bandeau l'assume (D1). */

function useWorkOrders() {
  return useQuery({
    queryKey: ['work-orders'],
    queryFn: async () => (await unwrap(await api.GET('/work-orders'))).workOrders,
  });
}

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 PageJournee() {
  const t = useTokens();
  const horsLigne = useHorsLigne();
  const { data: workOrders, refetch, isFetching, dataUpdatedAt } = useWorkOrders();

  const ots = triJournee(workOrders ?? []);
  const urgences = ots.filter((o) => o.priority === 'PERSON_TRAPPED');
  const jour = new Intl.DateTimeFormat('fr-FR', { weekday: 'long', day: 'numeric', month: 'short' })
    .format(new Date());

  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 }}>
            Ma journée
          </Text>
          <Text
            style={{
              marginLeft: 'auto',
              fontFamily: 'Manrope_600SemiBold',
              fontSize: 11,
              color: t.encre3,
            }}
          >
            {jour}
          </Text>
        </View>

        {horsLigne ? (
          <View
            style={{
              backgroundColor: t.stAttenteFond,
              borderColor: t.stAttente,
              borderWidth: 1,
              borderRadius: 10,
              padding: 9,
            }}
          >
            <Text style={{ color: t.stAttente, fontFamily: 'Manrope_700Bold', fontSize: 12 }}>
              ⚠ Hors-ligne — liste du{' '}
              {dataUpdatedAt
                ? new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit' }).format(dataUpdatedAt)
                : '…'}
              . Vos saisies partiront en file (R4.3).
            </Text>
          </View>
        ) : null}
        {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 en cours — 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>
  );
}
