import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import * as Location from 'expo-location';
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 { Button } from '../../components/ui/Button';
import { useToast } from '../../context/ToastContext';
import { useResponsive } from '../../hooks/useResponsive';
import { geofenceService } from '../../services/geofenceService';
import { checkinService } from '../../services/checkinService';
import { colors, spacing, radii } from '../../theme';

export default function JobCheckinScreen() {
  const navigation = useNavigation<any>();
  const route = useRoute<any>();
  const { jobId, jobStatus } = route.params;
  const { toast } = useToast();
  const { contentPadding, fontSize } = useResponsive();
  const [location, setLocation] = useState<Location.LocationObject | null>(null);
  const [locationError, setLocationError] = useState<string | null>(null);
  const [geofenceResult, setGeofenceResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [manualOverride, setManualOverride] = useState(false);
  const [overrideReason, setOverrideReason] = useState('');
  const [address, setAddress] = useState<string>('');

  useEffect(() => {
    getCurrentLocation();
  }, []);

  const getCurrentLocation = async (retryCount = 0) => {
    setRefreshing(true);
    setLocationError(null);
    try {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setLocationError('Location permission denied');
        setRefreshing(false);
        return;
      }

      let loc: Location.LocationObject | null = null;
      try {
        loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
      } catch {
        if (retryCount < 2) {
          try {
            loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
          } catch {}
        }
      }

      if (!loc && retryCount < 2) {
        setTimeout(() => getCurrentLocation(retryCount + 1), 1500);
        return;
      }

      if (!loc) {
        setLocationError('Failed to get location. Tap refresh to try again.');
        setRefreshing(false);
        return;
      }

      setLocation(loc);
      setLocationError(null);

      try {
        const [addr] = await Location.reverseGeocodeAsync({
          latitude: loc.coords.latitude,
          longitude: loc.coords.longitude,
        });
        if (addr) {
          const parts = [addr.name, addr.street, addr.city, addr.region, addr.postalCode].filter(Boolean);
          setAddress(parts.join(', '));
        }
      } catch {}

      try {
        const result = await geofenceService.check(loc.coords.latitude, loc.coords.longitude);
        setGeofenceResult(result);
      } catch {}
    } catch {
      setLocationError('Failed to get location');
    } finally {
      setRefreshing(false);
    }
  };

  const handleCheckIn = async () => {
    if (!location) {
      toast('Location not available', 'error');
      return;
    }

    setLoading(true);
    try {
      await checkinService.checkIn(jobId, {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
        accuracy: location.coords.accuracy || undefined,
        manual_override: manualOverride,
        override_reason: overrideReason || undefined,
      });
      toast('Checked in successfully', 'success');
      navigation.goBack();
    } catch (error: any) {
      toast(error.response?.data?.error || 'Check-in failed', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleCheckOut = async () => {
    if (!location) {
      toast('Location not available', 'error');
      return;
    }

    setLoading(true);
    try {
      await checkinService.checkOut(jobId, {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
        accuracy: location.coords.accuracy || undefined,
      });
      toast('Checked out successfully', 'success');
      navigation.goBack();
    } catch (error: any) {
      toast(error.response?.data?.error || 'Check-out failed', 'error');
    } finally {
      setLoading(false);
    }
  };

  const isCheckIn = jobStatus === 'DRAFT' || jobStatus === 'CHECKED_IN';

  return (
    <View style={styles.container}>
      <ScreenContainer
        title={isCheckIn ? 'Check In' : 'Check Out'}
        onBack={() => navigation.goBack()}
        loading={false}
        scroll={true}
        contentPadding={contentPadding}
        noBottomPad={true}
      >
        <AnimatedCard delay={0}>
          <Text style={[styles.sectionTitle, { fontSize: fontSize.h3, marginBottom: spacing.md }]}>Current Location</Text>
          {location ? (
            <View style={styles.locationInfo}>
              <View style={[styles.locationIcon, { backgroundColor: colors.primary[50] }]}>
                <Ionicons name="location" size={20} color={colors.primary[600]} />
              </View>
              <View style={styles.locationDetails}>
                <Text style={[styles.coords, { fontSize: fontSize.body }]}>
                  {location.coords.latitude.toFixed(6)}, {location.coords.longitude.toFixed(6)}
                </Text>
                {address ? (
                  <Text style={{ color: colors.gray[600], fontSize: fontSize.caption, marginTop: spacing.xs }} numberOfLines={2}>{address}</Text>
                ) : null}
                <Text style={[styles.accuracy, { fontSize: fontSize.caption, marginTop: spacing.xs }]}>
                  Accuracy: {location.coords.accuracy?.toFixed(1)}m
                </Text>
              </View>
            </View>
          ) : (
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.sm, paddingVertical: spacing.md }}>
              {refreshing ? (
                <ActivityIndicator size="small" color={colors.primary[500]} />
              ) : (
                <Ionicons name="warning-outline" size={18} color={colors.warning[500]} />
              )}
              <Text style={[styles.loadingText, { fontSize: fontSize.body }]}>
                {locationError || 'Getting location...'}
              </Text>
            </View>
          )}
        </AnimatedCard>

        <AnimatedCard delay={100} style={{ marginTop: spacing.md }}>
          <Text style={[styles.sectionTitle, { fontSize: fontSize.h3, marginBottom: spacing.md }]}>Geofence Status</Text>
          {geofenceResult ? (
            <View style={styles.geofenceResult}>
              <View style={[
                styles.geofenceIcon,
                { backgroundColor: geofenceResult.inside ? colors.success[50] : colors.danger[50] }
              ]}>
                <Ionicons
                  name={geofenceResult.inside ? 'checkmark-circle' : 'close-circle'}
                  size={24}
                  color={geofenceResult.inside ? colors.success[500] : colors.danger[500]}
                />
              </View>
              <Text style={[
                styles.geofenceText,
                { color: geofenceResult.inside ? colors.success[600] : colors.danger[600], fontSize: fontSize.body }
              ]}>
                {geofenceResult.inside ? 'Inside geofence' : 'Outside geofence'}
                {geofenceResult.distance_meters != null ? ` (${Math.round(geofenceResult.distance_meters)}m)` : ''}
              </Text>
            </View>
          ) : (
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.sm, paddingVertical: spacing.md }}>
              <ActivityIndicator size="small" color={colors.primary[500]} />
              <Text style={[styles.loadingText, { fontSize: fontSize.body }]}>Checking geofence...</Text>
            </View>
          )}
        </AnimatedCard>

        {!geofenceResult?.inside && (
          <AnimatedCard delay={200} style={{ marginTop: spacing.md }}>
            <TouchableOpacity
              style={styles.overrideToggle}
              onPress={() => setManualOverride(!manualOverride)}
              activeOpacity={0.7}
            >
              <View style={[
                styles.checkbox,
                manualOverride && styles.checkboxChecked
              ]}>
                {manualOverride && (
                  <Ionicons name="checkmark" size={14} color={colors.white} />
                )}
              </View>
              <Text style={[styles.overrideLabel, { fontSize: fontSize.body }]}>Manual Override</Text>
            </TouchableOpacity>

            {manualOverride && (
              <TextInput
                style={[styles.overrideInput, { marginTop: spacing.md, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, fontSize: fontSize.body, minHeight: 60 }]}
                placeholder="Reason for override"
                placeholderTextColor={colors.gray[400]}
                value={overrideReason}
                onChangeText={setOverrideReason}
                multiline
              />
            )}
          </AnimatedCard>
        )}

        <TouchableOpacity
          onPress={() => getCurrentLocation()}
          disabled={refreshing}
          style={styles.refreshButton}
          activeOpacity={0.7}
        >
          {refreshing ? (
            <ActivityIndicator size="small" color={colors.primary[600]} />
          ) : (
            <Ionicons name="refresh-outline" size={18} color={colors.primary[600]} />
          )}
          <Text style={[styles.refreshText, { fontSize: fontSize.body }]}>
            {refreshing ? 'Refreshing...' : 'Refresh Location'}
          </Text>
        </TouchableOpacity>

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

      <View style={[styles.footer, { padding: contentPadding }]}>
        <Button
          title={isCheckIn ? 'Check In' : 'Check Out'}
          onPress={isCheckIn ? handleCheckIn : handleCheckOut}
          loading={loading}
          disabled={loading || !location}
          size="lg"
          icon={isCheckIn ? 'log-in-outline' : 'log-out-outline'}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  sectionTitle: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  locationInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  locationIcon: {
    width: 40,
    height: 40,
    borderRadius: radii.lg,
    justifyContent: 'center',
    alignItems: 'center',
  },
  locationDetails: {
    flex: 1,
  },
  coords: {
    fontFamily: 'monospace',
    color: colors.gray[800],
  },
  accuracy: {
    color: colors.gray[500],
  },
  loadingText: {
    color: colors.gray[400],
    textAlign: 'center',
  },
  geofenceResult: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  geofenceIcon: {
    width: 40,
    height: 40,
    borderRadius: radii.lg,
    justifyContent: 'center',
    alignItems: 'center',
  },
  geofenceText: {
    fontWeight: '600',
  },
  overrideToggle: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderRadius: radii.sm,
    borderWidth: 2,
    borderColor: colors.gray[300],
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkboxChecked: {
    backgroundColor: colors.primary[600],
    borderColor: colors.primary[600],
  },
  overrideLabel: {
    color: colors.gray[700],
  },
  overrideInput: {
    backgroundColor: colors.gray[50],
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.gray[200],
    textAlignVertical: 'top',
    color: colors.gray[900],
  },
  refreshButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.sm,
    paddingVertical: spacing.md,
    marginTop: spacing.md,
  },
  refreshText: {
    color: colors.primary[600],
    fontWeight: '500',
  },
  footer: {
    backgroundColor: colors.white,
    borderTopWidth: 1,
    borderTopColor: colors.border,
    paddingBottom: 24,
  },
});
