import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, Linking } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import MapView, { Marker } from 'react-native-maps';
import { getPharmacy, getPharmacyMedicines } from '../../services/pharmacies';
import { subscribeToMedicine, unsubscribeFromMedicine } from '../../services/notifications';
import { useAuth } from '../../hooks/useAuth';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import { Pharmacy, PharmacyMedicine } from '../../types';

export default function PharmacyDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const { colors } = useThemeContext();
  const { isAuthenticated } = useAuth();
  const [pharmacy, setPharmacy] = useState<Pharmacy | null>(null);
  const [medicines, setMedicines] = useState<PharmacyMedicine[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [subscribedMeds, setSubscribedMeds] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (!id) return;

    const fetchPharmacy = async () => {
      try {
        const [pharmData, medData] = await Promise.all([
          getPharmacy(Number(id)),
          getPharmacyMedicines(Number(id)),
        ]);
        setPharmacy(pharmData);
        setMedicines(medData as PharmacyMedicine[]);
      } catch (error) {
        console.error('Error fetching pharmacy:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPharmacy();
  }, [id]);

  const handleCall = () => {
    if (pharmacy?.phone) {
      Linking.openURL(`tel:${pharmacy.phone}`);
    }
  };

  const handleDirections = () => {
    if (pharmacy) {
      const url = `https://www.google.com/maps/dir/?api=1&destination=${pharmacy.latitude},${pharmacy.longitude}`;
      Linking.openURL(url);
    }
  };

  const handleToggleMedSubscription = async (nregistro: string, medicineName: string) => {
    if (!isAuthenticated) return;
    const key = nregistro;
    const isSub = subscribedMeds.has(key);
    try {
      if (isSub) {
        await unsubscribeFromMedicine(nregistro, Number(id));
        setSubscribedMeds(prev => {
          const next = new Set(prev);
          next.delete(key);
          return next;
        });
      } else {
        await subscribeToMedicine(nregistro, medicineName, Number(id));
        setSubscribedMeds(prev => new Set(prev).add(key));
      }
    } catch {
      // silently fail
    }
  };

  if (isLoading) {
    return <LoadingSpinner message="Cargando farmacia..." />;
  }

  if (!pharmacy) {
    return (
      <View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
        <Text style={[styles.errorText, { color: colors.textSecondary }]}>Farmacia no encontrada</Text>
      </View>
    );
  }

  return (
    <ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={[styles.header, { backgroundColor: colors.card }]}>
        <Text style={[styles.name, { color: colors.text }]}>{pharmacy.name}</Text>
      </View>

      <View style={[styles.actionsRow, { backgroundColor: colors.card, borderBottomColor: colors.separator }]}>
        <TouchableOpacity style={styles.actionButton} onPress={handleCall}>
          <Ionicons name="call" size={20} color={colors.primary} />
          <Text style={[styles.actionText, { color: colors.primary }]}>Llamar</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.actionButton} onPress={handleDirections}>
          <Ionicons name="navigate" size={20} color={colors.primary} />
          <Text style={[styles.actionText, { color: colors.primary }]}>Cómo llegar</Text>
        </TouchableOpacity>
      </View>

      <View style={[styles.infoSection, { backgroundColor: colors.card }]}>
        <View style={styles.infoRow}>
          <Ionicons name="location" size={18} color={colors.textSecondary} />
          <Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.address}</Text>
        </View>

        {pharmacy.phone && (
          <View style={styles.infoRow}>
            <Ionicons name="call" size={18} color={colors.textSecondary} />
            <Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.phone}</Text>
          </View>
        )}
      </View>

      <View style={styles.mapContainer}>
        <MapView
          style={styles.map}
          initialRegion={{
            latitude: pharmacy.latitude,
            longitude: pharmacy.longitude,
            latitudeDelta: 0.01,
            longitudeDelta: 0.01,
          }}
          scrollEnabled={false}
        >
          <Marker
            coordinate={{
              latitude: pharmacy.latitude,
              longitude: pharmacy.longitude,
            }}
            title={pharmacy.name}
          />
        </MapView>
      </View>

      <View style={styles.medicinesSection}>
        <Text style={[styles.sectionTitle, { color: colors.text }]}>
          Medicamentos ({medicines.length})
        </Text>

        {medicines.length === 0 ? (
          <Text style={[styles.noMedicines, { color: colors.textSecondary }]}>No hay medicamentos disponibles</Text>
        ) : (
          medicines.map((med) => {
            const isSub = subscribedMeds.has(med.medicine_nregistro);
            return (
              <View key={med.id} style={[styles.medicineCard, { backgroundColor: colors.card }]}>
                <TouchableOpacity
                  style={styles.medicineCardContent}
                  onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
                >
                  <View style={styles.medicineInfo}>
                    <Text style={[styles.medicineName, { color: colors.text }]}>{med.medicine_name}</Text>
                    <Text style={[styles.medicineNregistro, { color: colors.textSecondary }]}>Reg: {med.medicine_nregistro}</Text>
                  </View>
                  <View style={styles.medicineStock}>
                    <Text style={[styles.price, { color: colors.primary }]}>{med.price.toFixed(2)} €</Text>
                    <Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {med.stock}</Text>
                  </View>
                </TouchableOpacity>
                {isAuthenticated && (
                  <TouchableOpacity
                    style={[styles.bellButton, { backgroundColor: isSub ? colors.primary : colors.surfaceVariant, borderTopColor: colors.border }]}
                    onPress={() => handleToggleMedSubscription(med.medicine_nregistro, med.medicine_name)}
                  >
                    <Ionicons
                      name={isSub ? 'notifications' : 'notifications-outline'}
                      size={18}
                      color={isSub ? '#fff' : colors.textSecondary}
                    />
                    <Text style={[styles.bellText, { color: isSub ? '#fff' : colors.textSecondary }]}>
                      {isSub ? 'Notificaciones activas' : 'Notificarme cuando haya stock'}
                    </Text>
                  </TouchableOpacity>
                )}
              </View>
            );
          })
        )}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    padding: spacing.md,
  },
  name: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  actionsRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: spacing.md,
    borderBottomWidth: 1,
  },
  actionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: spacing.sm,
  },
  actionText: {
    marginLeft: spacing.xs,
    fontWeight: '500',
  },
  infoSection: {
    padding: spacing.md,
    marginTop: spacing.sm,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: spacing.sm,
  },
  infoText: {
    flex: 1,
    marginLeft: spacing.sm,
    fontSize: 16,
  },
  mapContainer: {
    height: 200,
    marginTop: spacing.sm,
  },
  map: {
    flex: 1,
  },
  medicinesSection: {
    marginTop: spacing.sm,
    padding: spacing.md,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: spacing.md,
  },
  noMedicines: {
    textAlign: 'center',
    padding: spacing.xl,
  },
  medicineCard: {
    borderRadius: borderRadius.md,
    marginBottom: spacing.sm,
    overflow: 'hidden',
  },
  medicineCardContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: spacing.md,
  },
  medicineInfo: {
    flex: 1,
  },
  medicineName: {
    fontSize: 16,
    fontWeight: '500',
  },
  medicineNregistro: {
    fontSize: 12,
    marginTop: spacing.xs,
  },
  medicineStock: {
    alignItems: 'flex-end',
  },
  price: {
    fontSize: 16,
    fontWeight: '600',
  },
  stock: {
    fontSize: 12,
    marginTop: spacing.xs,
  },
  bellButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.xs,
    paddingVertical: spacing.sm,
    borderTopWidth: 1,
  },
  bellText: {
    fontSize: 13,
    fontWeight: '600',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    fontSize: 16,
  },
});
