import React, { useState, useCallback, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Modal } from 'react-native';
import * as Location from 'expo-location';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
import { Button } from '../../components/ui/Button';
import { GeofenceMap } from '../../components/geofence/GeofenceMap';
import { useToast } from '../../context/ToastContext';
import { useResponsive } from '../../hooks/useResponsive';
import { geofenceService } from '../../services/geofenceService';
import { Geofence } from '../../types';
import { colors, spacing, radii } from '../../theme';

interface GeofenceWithLocation extends Geofence {
  locationName?: string;
}

const DUMMY_CHENNAI_GEOFENCES: GeofenceWithLocation[] = [
  {
    id: 1001,
    company_id: 1,
    name: 'Chennai Central Station',
    type: 'CIRCLE',
    latitude: 13.0827,
    longitude: 80.2707,
    radius: 500,
    status: 'ACTIVE',
    created_by: 1,
    locationName: 'Chennai Central, George Town, Chennai, Tamil Nadu 600003',
  },
  {
    id: 1002,
    company_id: 1,
    name: 'T Nagar Office',
    type: 'CIRCLE',
    latitude: 13.0418,
    longitude: 80.2341,
    radius: 300,
    status: 'ACTIVE',
    created_by: 1,
    locationName: 'Thyagaraya Nagar, T Nagar, Chennai, Tamil Nadu 600017',
  },
  {
    id: 1003,
    company_id: 1,
    name: 'OMR Tech Park',
    type: 'CIRCLE',
    latitude: 12.9165,
    longitude: 80.2272,
    radius: 750,
    status: 'ACTIVE',
    created_by: 1,
    locationName: 'Old Mahabalipuram Road, Sholinganallur, Chennai, Tamil Nadu 600119',
  },
  {
    id: 1004,
    company_id: 1,
    name: 'Adyar Branch',
    type: 'CIRCLE',
    latitude: 13.0063,
    longitude: 80.2574,
    radius: 400,
    status: 'ACTIVE',
    created_by: 1,
    locationName: 'Adyar, Chennai, Tamil Nadu 600020',
  },
  {
    id: 1005,
    company_id: 1,
    name: 'Velachery Warehouse',
    type: 'CIRCLE',
    latitude: 12.9815,
    longitude: 80.2180,
    radius: 600,
    status: 'ACTIVE',
    created_by: 1,
    locationName: 'Velachery, Chennai, Tamil Nadu 600042',
  },
];

export default function GeofenceListScreen() {
  const navigation = useNavigation<any>();
  const { toast } = useToast();
  const { contentPadding, fontSize } = useResponsive();
  const [geofences, setGeofences] = useState<Geofence[]>([]);
  const [locationNames, setLocationNames] = useState<Record<number, string>>({});
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const [showForm, setShowForm] = useState(false);
  const [editTarget, setEditTarget] = useState<Geofence | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Geofence | null>(null);
  const [saving, setSaving] = useState(false);
  const [fetchingLocation, setFetchingLocation] = useState(false);

  const [formName, setFormName] = useState('');
  const [formLat, setFormLat] = useState('');
  const [formLng, setFormLng] = useState('');
  const [formRadius, setFormRadius] = useState('');
  const [errors, setErrors] = useState<{ name?: string; lat?: string; lng?: string; radius?: string }>({});

  const loadData = async () => {
    try {
      const data = await geofenceService.list();
      setGeofences(data);
      if (data.length > 0) {
        fetchLocationNamesForGeofences(data);
      }
    } catch (error) {
      console.error('Failed to load geofences:', error);
      setGeofences([]);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

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

  const fetchLocationNamesForGeofences = async (geofenceData: Geofence[]) => {
    const names: Record<number, string> = {};

    for (const g of geofenceData) {
      try {
        const result = await Location.reverseGeocodeAsync({
          latitude: g.latitude,
          longitude: g.longitude,
        });

        if (result.length > 0) {
          const loc = result[0];
          const parts = [
            loc.name,
            loc.street,
            loc.district,
            loc.city,
            loc.region,
            loc.postalCode,
          ].filter(Boolean);
          names[g.id] = parts.join(', ');
        }
      } catch (error) {
        names[g.id] = `${Number(g.latitude).toFixed(4)}, ${Number(g.longitude).toFixed(4)}`;
      }
    }

    setLocationNames(names);
  };

  const resetForm = () => {
    setFormName('');
    setFormLat('');
    setFormLng('');
    setFormRadius('');
    setErrors({});
  };

  const openCreate = () => {
    resetForm();
    setEditTarget(null);
    setShowForm(true);
  };

  const openEdit = (g: Geofence) => {
    setEditTarget(g);
    setFormName(g.name);
    setFormLat(g.latitude.toString());
    setFormLng(g.longitude.toString());
    setFormRadius(g.radius.toString());
    setErrors({});
    setShowForm(true);
  };

  const autoFillLocation = async () => {
    setFetchingLocation(true);
    try {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        toast('Location permission denied', 'error');
        return;
      }
      const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
      setFormLat(loc.coords.latitude.toFixed(6));
      setFormLng(loc.coords.longitude.toFixed(6));
      toast('Location fetched', 'success');
    } catch {
      toast('Failed to get location', 'error');
    } finally {
      setFetchingLocation(false);
    }
  };

  const validate = () => {
    const e: typeof errors = {};
    if (!formName.trim()) e.name = 'Name is required';
    if (!formLat.trim()) e.lat = 'Latitude is required';
    if (!formLng.trim()) e.lng = 'Longitude is required';
    if (!formRadius.trim()) e.radius = 'Radius is required';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSave = async () => {
    if (!validate()) return;
    setSaving(true);
    try {
      const payload = {
        name: formName.trim(),
        latitude: parseFloat(formLat),
        longitude: parseFloat(formLng),
        radius: parseFloat(formRadius),
      };
      if (editTarget) {
        await geofenceService.update(editTarget.id, payload);
        toast('Geofence updated', 'success');
      } else {
        await geofenceService.create(payload);
        toast('Geofence created', 'success');
      }
      setShowForm(false);
      resetForm();
      setEditTarget(null);
      loadData();
    } catch (error: any) {
      toast(error.response?.data?.message || 'Failed to save geofence', 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await geofenceService.remove(deleteTarget.id);
      toast('Geofence deleted', 'success');
      setDeleteTarget(null);
      loadData();
    } catch (error: any) {
      toast(error.response?.data?.message || 'Failed to delete geofence', 'error');
    }
  };

  const displayGeofences = geofences.length > 0 ? geofences : DUMMY_CHENNAI_GEOFENCES;
  const isShowingDummy = geofences.length === 0;

  return (
    <ScreenContainer
      title="Geofences"
      subtitle={`${displayGeofences.length} active`}
      onBack={() => navigation.goBack()}
      loading={loading}
      refreshing={refreshing}
      onRefresh={onRefresh}
      scroll={true}
      contentPadding={contentPadding}
      rightAction={{ icon: 'add-circle-outline', onPress: openCreate }}
    >
      <View style={[styles.mapSection, { marginBottom: spacing.lg }]}>
        <GeofenceMap
          geofences={displayGeofences}
          height={280}
          showLocationNames={true}
        />
      </View>

      {isShowingDummy && (
        <View style={[styles.demoBanner, { backgroundColor: colors.warning[50], borderColor: colors.warning[500] }]}>
          <Ionicons name="information-circle-outline" size={16} color={colors.warning[600]} />
          <Text style={[styles.demoBannerText, { color: colors.warning[700], fontSize: fontSize.caption }]}>
            Showing demo Chennai geofences. Create your own to get started!
          </Text>
        </View>
      )}

      <View style={[styles.sectionHeader, { marginBottom: spacing.md }]}>
        <Text style={[styles.sectionTitle, { fontSize: fontSize.h3, color: colors.gray[900] }]}>
          All Geofences
        </Text>
        <TouchableOpacity onPress={openCreate} style={[styles.addButton, { backgroundColor: colors.primary[50] }]}>
          <Ionicons name="add" size={18} color={colors.primary[600]} />
          <Text style={[styles.addButtonText, { color: colors.primary[600], fontSize: fontSize.caption }]}>
            Add New
          </Text>
        </TouchableOpacity>
      </View>

      {displayGeofences.length > 0 ? (
        displayGeofences.map((g, index) => (
          <AnimatedCard key={g.id} delay={index * 60} style={{ marginBottom: spacing.sm }}>
            <View style={[styles.card, { gap: spacing.md }]}>
              <View style={[styles.iconContainer, { backgroundColor: colors.primary[50] }]}>
                <Ionicons name="location-outline" size={22} color={colors.primary[600]} />
              </View>
              <View style={styles.info}>
                <Text style={[styles.name, { fontSize: fontSize.body }]}>{g.name}</Text>
                <Text style={[styles.detail, { fontSize: fontSize.caption, marginTop: spacing.xs }]}>
                  {Number(g.latitude).toFixed(6)}, {Number(g.longitude).toFixed(6)}
                </Text>
                {locationNames[g.id] && (
                  <View style={[styles.addressContainer, { backgroundColor: colors.gray[50] }]}>
                    <Ionicons name="location-sharp" size={12} color={colors.gray[400]} />
                    <Text style={[styles.addressText, { color: colors.gray[600], fontSize: fontSize.caption }]} numberOfLines={1}>
                      {locationNames[g.id]}
                    </Text>
                  </View>
                )}
                <View style={[styles.radiusContainer, { marginTop: spacing.xs }]}>
                  <Ionicons name="resize-outline" size={12} color={colors.primary[500]} />
                  <Text style={[styles.radiusText, { color: colors.primary[600], fontSize: fontSize.caption }]}>
                    {Number(g.radius)}m radius
                  </Text>
                </View>
              </View>
              <View style={styles.actions}>
                <TouchableOpacity
                  onPress={() => openEdit(g)}
                  style={[styles.actionBtn, { backgroundColor: colors.primary[50] }]}
                >
                  <Ionicons name="create-outline" size={18} color={colors.primary[600]} />
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={() => setDeleteTarget(g)}
                  style={[styles.actionBtn, { backgroundColor: colors.danger[50] }]}
                >
                  <Ionicons name="trash-outline" size={18} color={colors.danger[600]} />
                </TouchableOpacity>
              </View>
            </View>
          </AnimatedCard>
        ))
      ) : (
        <EmptyState
          icon="location-outline"
          title="No geofences"
          description="Create your first geofence to get started"
          action={
            <Button title="Create Geofence" onPress={openCreate} variant="secondary" size="sm" />
          }
        />
      )}

      <Modal visible={showForm} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={[styles.modalContent, { paddingTop: spacing.xl }]}>
            <View style={styles.modalHeader}>
              <Text style={[styles.modalTitle, { fontSize: fontSize.h3 }]}>{editTarget ? 'Edit Geofence' : 'New Geofence'}</Text>
              <TouchableOpacity onPress={() => { setShowForm(false); setEditTarget(null); resetForm(); }}>
                <Ionicons name="close" size={24} color={colors.gray[500]} />
              </TouchableOpacity>
            </View>

            <View style={{ gap: spacing.md }}>
              <View>
                <Text style={[styles.fieldLabel, { fontSize: fontSize.caption }]}>Name *</Text>
                <View style={[styles.input, { borderColor: errors.name ? colors.danger[500] : colors.border }]}>
                  <TextInput value={formName} onChangeText={setFormName} placeholder="Geofence name" placeholderTextColor={colors.gray[400]} style={[styles.inputText, { fontSize: fontSize.body }]} />
                </View>
                {errors.name && <Text style={styles.errorText}>{errors.name}</Text>}
              </View>

              <View style={styles.locationHeader}>
                <Text style={[styles.fieldLabel, { fontSize: fontSize.caption }]}>Coordinates</Text>
                <TouchableOpacity style={[styles.autoFillBtn, fetchingLocation && { opacity: 0.6 }]} onPress={autoFillLocation} disabled={fetchingLocation}>
                  <Ionicons name={fetchingLocation ? 'refresh' : 'locate'} size={14} color={colors.primary[600]} />
                  <Text style={[styles.autoFillText, { fontSize: fontSize.caption }]}>{fetchingLocation ? 'Fetching...' : 'Use Current Location'}</Text>
                </TouchableOpacity>
              </View>

              <View style={{ flexDirection: 'row', gap: spacing.md }}>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.fieldLabel, { fontSize: fontSize.caption }]}>Latitude *</Text>
                  <View style={[styles.input, { borderColor: errors.lat ? colors.danger[500] : colors.border }]}>
                    <TextInput value={formLat} onChangeText={setFormLat} placeholder="0.000000" placeholderTextColor={colors.gray[400]} keyboardType="numeric" style={[styles.inputText, { fontSize: fontSize.body }]} />
                  </View>
                  {errors.lat && <Text style={styles.errorText}>{errors.lat}</Text>}
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.fieldLabel, { fontSize: fontSize.caption }]}>Longitude *</Text>
                  <View style={[styles.input, { borderColor: errors.lng ? colors.danger[500] : colors.border }]}>
                    <TextInput value={formLng} onChangeText={setFormLng} placeholder="0.000000" placeholderTextColor={colors.gray[400]} keyboardType="numeric" style={[styles.inputText, { fontSize: fontSize.body }]} />
                  </View>
                  {errors.lng && <Text style={styles.errorText}>{errors.lng}</Text>}
                </View>
              </View>

              <View>
                <Text style={[styles.fieldLabel, { fontSize: fontSize.caption }]}>Radius (meters) *</Text>
                <View style={[styles.input, { borderColor: errors.radius ? colors.danger[500] : colors.border }]}>
                  <TextInput value={formRadius} onChangeText={setFormRadius} placeholder="100" placeholderTextColor={colors.gray[400]} keyboardType="numeric" style={[styles.inputText, { fontSize: fontSize.body }]} />
                </View>
                {errors.radius && <Text style={styles.errorText}>{errors.radius}</Text>}
              </View>
            </View>

            <View style={{ marginTop: spacing.xl, gap: spacing.sm }}>
              <Button title={editTarget ? 'Update Geofence' : 'Create Geofence'} onPress={handleSave} loading={saving} disabled={saving} />
              <Button title="Cancel" onPress={() => { setShowForm(false); setEditTarget(null); resetForm(); }} variant="secondary" />
            </View>
          </View>
        </View>
      </Modal>

      <ConfirmDialog
        visible={!!deleteTarget}
        title="Delete Geofence"
        message={`Are you sure you want to delete "${deleteTarget?.name}"? This action cannot be undone.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
        danger
      />
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  mapSection: {
    borderRadius: radii.lg,
    overflow: 'hidden',
  },
  demoBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    padding: spacing.md,
    borderRadius: radii.md,
    borderWidth: 1,
    marginBottom: spacing.md,
  },
  demoBannerText: {
    flex: 1,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  sectionTitle: {
    fontWeight: '700',
  },
  addButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: radii.md,
  },
  addButtonText: {
    fontWeight: '600',
  },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  iconContainer: {
    width: 44,
    height: 44,
    borderRadius: radii.lg,
    justifyContent: 'center',
    alignItems: 'center',
  },
  info: {
    flex: 1,
  },
  name: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  detail: {
    color: colors.gray[500],
  },
  addressContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    marginTop: spacing.xs,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    borderRadius: radii.sm,
  },
  addressText: {
    flex: 1,
  },
  radiusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
  },
  radiusText: {
    fontWeight: '500',
  },
  actions: {
    gap: spacing.xs,
  },
  actionBtn: {
    width: 36,
    height: 36,
    borderRadius: radii.md,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: colors.white,
    borderTopLeftRadius: radii.xl,
    borderTopRightRadius: radii.xl,
    padding: spacing.xl,
    maxHeight: '90%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.xl,
  },
  modalTitle: {
    fontWeight: '700',
    color: colors.gray[900],
  },
  fieldLabel: {
    fontWeight: '600',
    color: colors.gray[700],
    marginBottom: spacing.xs,
  },
  input: {
    borderWidth: 1,
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    backgroundColor: colors.white,
  },
  inputText: {
    color: colors.gray[900],
    padding: 0,
  },
  errorText: {
    color: colors.danger[600],
    fontSize: 12,
    marginTop: 2,
  },
  locationHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  autoFillBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    backgroundColor: colors.primary[50],
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.primary[200],
  },
  autoFillText: {
    color: colors.primary[600],
    fontWeight: '600',
  },
});
