import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  TextInput,
  Modal,
  Animated,
  Pressable,
  Dimensions,
  Platform,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Play, Square, ChevronDown, Check } from 'lucide-react-native';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFonts, Inter_400Regular, Inter_600SemiBold } from '@expo-google-fonts/inter';

const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;
const SCREEN_HEIGHT = Dimensions.get('window').height;
const SHEET_HEIGHT = SCREEN_HEIGHT * 0.75;

const INSOLE_TYPES = ['Kurk', 'Berk', '3D'] as const;
type InsoleType = (typeof INSOLE_TYPES)[number];

export default function TimerScreen() {
  const insets = useSafeAreaInsets();
  const queryClient = useQueryClient();
  // fontError: if fonts fail to load on Android we still render (no freeze)
  const [fontsLoaded, fontError] = useFonts({ Inter_400Regular, Inter_600SemiBold });

  const [activeTaskId, setActiveTaskId] = useState<number | null>(null);
  const [insoleType, setInsoleType] = useState<InsoleType>('Kurk');
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [startTime, setStartTime] = useState<Date | null>(null);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [showPicker, setShowPicker] = useState(false);
  const [discardPending, setDiscardPending] = useState(false);
  const [insoleCount, setInsoleCount] = useState(2);
  const [insoleCountText, setInsoleCountText] = useState('2');

  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const discardTimerRef = useRef<NodeJS.Timeout | null>(null);
  const slideAnim = useRef(new Animated.Value(SHEET_HEIGHT)).current;

  const { data: tasks = [] } = useQuery({
    queryKey: ['tasks'],
    queryFn: async () => {
      const res = await fetch(`${BASE_URL}/api/tasks`);
      if (!res.ok) throw new Error('Failed to fetch tasks');
      return res.json();
    },
  });

  const saveLogMutation = useMutation({
    mutationFn: async (log: any) => {
      const res = await fetch(`${BASE_URL}/api/logs`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(log),
      });
      if (!res.ok) throw new Error('Failed to save log');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['logs'] });
    },
  });

  useEffect(() => {
    if (isRunning && !isPaused) {
      timerRef.current = setInterval(() => setElapsedTime((prev) => prev + 1), 1000);
    } else {
      if (timerRef.current) clearInterval(timerRef.current);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isRunning, isPaused]);

  const openPicker = () => {
    setShowPicker(true);
    Animated.timing(slideAnim, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  const closePicker = () => {
    Animated.timing(slideAnim, {
      toValue: SHEET_HEIGHT,
      duration: 250,
      useNativeDriver: true,
    }).start(() => setShowPicker(false));
  };

  const handleStart = () => {
    if (!activeTaskId) return;
    setIsRunning(true);
    setIsPaused(false);
    setStartTime(new Date());
  };

  const handlePause = () => setIsPaused(true);
  const handleResume = () => setIsPaused(false);

  const handleStop = () => {
    if (!activeTaskId || !startTime) return;
    setIsRunning(false);
    setIsPaused(false);
    const endTime = new Date();
    saveLogMutation.mutate({
      task_id: activeTaskId,
      start_time: startTime.toISOString(),
      end_time: endTime.toISOString(),
      duration_seconds: elapsedTime,
      pair_count: insoleCount,
      insole_type: insoleType,
    });
    setStartTime(null);
    setElapsedTime(0);
    setDiscardPending(false);
    if (discardTimerRef.current) clearTimeout(discardTimerRef.current);
  };

  const handleDiscard = () => {
    if (!discardPending) {
      setDiscardPending(true);
      discardTimerRef.current = setTimeout(() => setDiscardPending(false), 3000);
    } else {
      if (discardTimerRef.current) clearTimeout(discardTimerRef.current);
      setIsRunning(false);
      setIsPaused(false);
      setStartTime(null);
      setElapsedTime(0);
      setDiscardPending(false);
    }
  };

  const handleInsoleCountChange = (text: string) => {
    setInsoleCountText(text);
    const parsed = parseInt(text, 10);
    if (!isNaN(parsed) && parsed > 0) setInsoleCount(parsed);
  };

  const adjustInsoleCount = (delta: number) => {
    const next = Math.max(1, insoleCount + delta);
    setInsoleCount(next);
    setInsoleCountText(String(next));
  };

  const formatTime = (seconds: number) => {
    const hrs = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // Wait for fonts — but if font loading errored, render anyway (prevents Android freeze)
  if (!fontsLoaded && !fontError) return null;

  const regular = fontError ? undefined : 'Inter_400Regular';
  const semibold = fontError ? undefined : 'Inter_600SemiBold';

  const selectedTask = tasks.find((t: any) => t.id === activeTaskId);
  const canStart = !!activeTaskId;

  const filteredTasks = tasks.filter((t: any) =>
    Array.isArray(t.insole_types) ? t.insole_types.includes(insoleType) : true
  );

  return (
    <View style={{ flex: 1, backgroundColor: '#ffffff', paddingTop: insets.top }}>
      <ScrollView contentContainerStyle={{ padding: 24 }}>
        {/* 1. Type zool */}
        <View style={{ marginBottom: 24 }}>
          <Text
            style={{
              fontSize: 12,
              fontWeight: '500',
              color: '#6B7280',
              marginBottom: 8,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
              fontFamily: semibold,
            }}
          >
            Type zool
          </Text>
          <View style={{ flexDirection: 'row' }}>
            {INSOLE_TYPES.map((type, i) => {
              const selected = insoleType === type;
              return (
                <TouchableOpacity
                  key={type}
                  onPress={() => {
                    if (isRunning) return;
                    setInsoleType(type);
                    setActiveTaskId(null);
                  }}
                  disabled={isRunning}
                  style={{
                    flex: 1,
                    paddingVertical: 14,
                    borderRadius: 12,
                    borderWidth: 2,
                    borderColor: selected ? '#2563EB' : '#E5E7EB',
                    backgroundColor: selected ? '#EFF6FF' : '#F9FAFB',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: i < INSOLE_TYPES.length - 1 ? 10 : 0,
                  }}
                >
                  <Text
                    style={{
                      fontSize: 16,
                      fontWeight: '600',
                      color: selected ? '#2563EB' : isRunning ? '#9CA3AF' : '#374151',
                      fontFamily: semibold,
                    }}
                  >
                    {type}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>

        {/* 2. Type handeling */}
        <View style={{ marginBottom: 24 }}>
          <Text
            style={{
              fontSize: 12,
              fontWeight: '500',
              color: '#6B7280',
              marginBottom: 8,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
              fontFamily: semibold,
            }}
          >
            Type handeling
          </Text>
          <TouchableOpacity
            onPress={() => !isRunning && openPicker()}
            disabled={isRunning}
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: 16,
              paddingVertical: 14,
              backgroundColor: isRunning ? '#F9FAFB' : '#ffffff',
              borderWidth: 1,
              borderColor: '#E5E7EB',
              borderRadius: 12,
            }}
          >
            <Text
              style={{
                fontSize: 16,
                color: activeTaskId ? '#111827' : '#9CA3AF',
                fontFamily: regular,
              }}
            >
              {selectedTask ? selectedTask.name : 'Kies een handeling...'}
            </Text>
            <ChevronDown color="#6B7280" size={20} />
          </TouchableOpacity>
        </View>

        {/* 3. Aantal zolen */}
        <View style={{ marginBottom: 40 }}>
          <Text
            style={{
              fontSize: 12,
              fontWeight: '500',
              color: '#6B7280',
              marginBottom: 8,
              textTransform: 'uppercase',
              letterSpacing: 0.5,
              fontFamily: semibold,
            }}
          >
            Aantal zolen
          </Text>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'stretch',
              borderWidth: 1,
              borderColor: '#E5E7EB',
              borderRadius: 12,
              overflow: 'hidden',
            }}
          >
            <TouchableOpacity
              onPress={() => adjustInsoleCount(-1)}
              disabled={isRunning || insoleCount <= 1}
              style={{
                width: 64,
                backgroundColor: '#F9FAFB',
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: 14,
              }}
            >
              <Text
                style={{
                  fontSize: 28,
                  lineHeight: 34,
                  color: insoleCount <= 1 || isRunning ? '#D1D5DB' : '#111827',
                  fontFamily: semibold,
                  textAlign: 'center',
                }}
              >
                −
              </Text>
            </TouchableOpacity>
            <TextInput
              value={insoleCountText}
              onChangeText={handleInsoleCountChange}
              keyboardType="number-pad"
              editable={!isRunning}
              style={{
                flex: 1,
                textAlign: 'center',
                fontSize: 22,
                fontWeight: '600',
                color: isRunning ? '#9CA3AF' : '#111827',
                fontFamily: semibold,
                paddingVertical: Platform.OS === 'android' ? 10 : 14,
                paddingHorizontal: 0,
              }}
            />
            <TouchableOpacity
              onPress={() => adjustInsoleCount(1)}
              disabled={isRunning}
              style={{
                width: 64,
                backgroundColor: '#F9FAFB',
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: 14,
              }}
            >
              <Text
                style={{
                  fontSize: 28,
                  lineHeight: 34,
                  color: isRunning ? '#D1D5DB' : '#111827',
                  fontFamily: semibold,
                  textAlign: 'center',
                }}
              >
                +
              </Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* 4. Stopwatch display */}
        <TouchableOpacity
          onPress={() => {
            if (!isRunning && canStart) handleStart();
            else if (isRunning) {
              if (isPaused) handleResume();
              else handlePause();
            }
          }}
          activeOpacity={canStart || isRunning ? 0.75 : 1}
          style={{
            alignItems: 'center',
            justifyContent: 'center',
            paddingVertical: 60,
            backgroundColor: '#F9FAFB',
            borderRadius: 24,
            borderWidth: 1,
            borderColor: isPaused ? '#FDE68A' : '#E5E7EB',
          }}
        >
          <Text
            style={{
              fontSize: 64,
              fontWeight: '600',
              color: isRunning ? (isPaused ? '#D97706' : '#111827') : '#9CA3AF',
              fontFamily: semibold,
              letterSpacing: -2,
            }}
          >
            {formatTime(elapsedTime)}
          </Text>
          {isRunning ? (
            <View
              style={{
                marginTop: 16,
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: isPaused ? '#FFFBEB' : '#EFF6FF',
                paddingHorizontal: 12,
                paddingVertical: 6,
                borderRadius: 999,
              }}
            >
              <View
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: 4,
                  backgroundColor: isPaused ? '#F59E0B' : '#2563EB',
                  marginRight: 8,
                }}
              />
              <Text
                style={{
                  fontSize: 12,
                  color: isPaused ? '#D97706' : '#2563EB',
                  fontWeight: '500',
                  fontFamily: semibold,
                }}
              >
                {isPaused ? 'Gepauzeerd — tik om te hervatten' : 'Tik om te pauzeren'}
              </Text>
            </View>
          ) : canStart ? (
            <View
              style={{
                marginTop: 16,
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#EFF6FF',
                paddingHorizontal: 12,
                paddingVertical: 6,
                borderRadius: 999,
              }}
            >
              <View
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: 4,
                  backgroundColor: '#2563EB',
                  marginRight: 8,
                }}
              />
              <Text
                style={{ fontSize: 12, color: '#2563EB', fontWeight: '500', fontFamily: semibold }}
              >
                Tik om te starten
              </Text>
            </View>
          ) : null}
        </TouchableOpacity>

        {/* 5. Knoppen */}
        <View style={{ marginTop: 40 }}>
          {!isRunning ? (
            <TouchableOpacity
              onPress={handleStart}
              disabled={!canStart}
              style={{
                backgroundColor: canStart ? '#2563EB' : '#E5E7EB',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: 18,
                borderRadius: 16,
              }}
            >
              <Play
                fill={canStart ? 'white' : '#9CA3AF'}
                color={canStart ? 'white' : '#9CA3AF'}
                size={24}
                style={{ marginRight: 8 }}
              />
              <Text
                style={{
                  color: canStart ? 'white' : '#9CA3AF',
                  fontSize: 18,
                  fontWeight: '600',
                  fontFamily: semibold,
                }}
              >
                Start Stopwatch
              </Text>
            </TouchableOpacity>
          ) : (
            <>
              <TouchableOpacity
                onPress={handleStop}
                style={{
                  backgroundColor: '#DC2626',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingVertical: 18,
                  borderRadius: 16,
                  marginBottom: 12,
                }}
              >
                <Square fill="white" color="white" size={22} style={{ marginRight: 8 }} />
                <Text
                  style={{ color: 'white', fontSize: 18, fontWeight: '600', fontFamily: semibold }}
                >
                  Stop & Opslaan
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={handleDiscard}
                style={{
                  backgroundColor: discardPending ? '#374151' : '#F3F4F6',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingVertical: 18,
                  borderRadius: 16,
                }}
              >
                <Text
                  style={{
                    color: discardPending ? '#ffffff' : '#6B7280',
                    fontSize: 18,
                    fontWeight: '600',
                    fontFamily: semibold,
                  }}
                >
                  {discardPending ? 'Nogmaals tikken ter bevestiging' : 'Annuleren'}
                </Text>
              </TouchableOpacity>
            </>
          )}
        </View>
      </ScrollView>

      {/* Bottom Sheet — uses Pressable instead of nested TouchableWithoutFeedback (Android fix) */}
      <Modal
        visible={showPicker}
        transparent
        animationType="none"
        onRequestClose={closePicker}
        statusBarTranslucent
      >
        <View style={{ flex: 1 }}>
          {/* Backdrop */}
          <Pressable
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundColor: 'rgba(0,0,0,0.45)',
            }}
            onPress={closePicker}
          />
          {/* Sheet */}
          <Animated.View
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              height: SHEET_HEIGHT,
              backgroundColor: '#ffffff',
              borderTopLeftRadius: 24,
              borderTopRightRadius: 24,
              transform: [{ translateY: slideAnim }],
            }}
          >
            {/* Drag handle */}
            <View style={{ alignItems: 'center', paddingTop: 12, paddingBottom: 4 }}>
              <View style={{ width: 40, height: 4, borderRadius: 2, backgroundColor: '#D1D5DB' }} />
            </View>

            {/* Sheet header */}
            <View
              style={{
                paddingHorizontal: 24,
                paddingTop: 12,
                paddingBottom: 16,
                borderBottomWidth: 1,
                borderBottomColor: '#F3F4F6',
              }}
            >
              <Text
                style={{ fontSize: 18, fontWeight: '600', color: '#111827', fontFamily: semibold }}
              >
                Type handeling
              </Text>
              <Text style={{ fontSize: 13, color: '#6B7280', marginTop: 2, fontFamily: regular }}>
                Kies een handeling
              </Text>
            </View>

            {/* Task list */}
            <ScrollView
              contentContainerStyle={{ paddingVertical: 8, paddingBottom: insets.bottom + 32 }}
              showsVerticalScrollIndicator={false}
            >
              {filteredTasks.length === 0 ? (
                <View style={{ alignItems: 'center', paddingTop: 48, paddingHorizontal: 32 }}>
                  <Text
                    style={{
                      fontSize: 15,
                      color: '#9CA3AF',
                      textAlign: 'center',
                      fontFamily: regular,
                    }}
                  >
                    Geen handelingen beschikbaar voor {insoleType} zolen. Voeg ze toe via
                    Instellingen.
                  </Text>
                </View>
              ) : (
                filteredTasks.map((task: any) => {
                  const selected = activeTaskId === task.id;
                  return (
                    <TouchableOpacity
                      key={task.id}
                      onPress={() => {
                        setActiveTaskId(task.id);
                        closePicker();
                      }}
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        paddingHorizontal: 24,
                        paddingVertical: 18,
                        backgroundColor: selected ? '#F0F7FF' : '#ffffff',
                        borderBottomWidth: 1,
                        borderBottomColor: '#F3F4F6',
                      }}
                    >
                      <Text
                        style={{
                          flex: 1,
                          fontSize: 16,
                          color: selected ? '#2563EB' : '#374151',
                          fontFamily: selected ? semibold : regular,
                        }}
                      >
                        {task.name}
                      </Text>
                      {selected && <Check size={20} color="#2563EB" />}
                    </TouchableOpacity>
                  );
                })
              )}
            </ScrollView>
          </Animated.View>
        </View>
      </Modal>
    </View>
  );
}
