import React, { useState } from "react";
import { Text, TextInput, Pressable, StyleSheet, ScrollView, Alert } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import NetInfo from "@react-native-community/netinfo";
import { RootStackParamList } from "../navigation/types";
import { findPossibleDuplicateStores, insertLocalStore } from "../db/repository";
import { api } from "../api/client";
import { generateUuid } from "../utils/uuid";
import { MedicalStore } from "../types";
import { runSync } from "../sync/syncManager";
import { useAreaStore } from "../store/areaStore";

type Props = NativeStackScreenProps<RootStackParamList, "StoreForm">;

export default function StoreFormScreen({ navigation }: Props) {
  const selectedAreaId = useAreaStore((s) => s.selectedAreaId);
  const selectedAreaName = useAreaStore((s) => s.selectedAreaName);
  const [name, setName] = useState("");
  const [contactName, setContactName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [city, setCity] = useState("");
  const [saving, setSaving] = useState(false);

  const saveStore = async () => {
    if (!name.trim()) {
      Alert.alert("Store name is required");
      return;
    }
    setSaving(true);
    try {
      const duplicates = await findPossibleDuplicateStores(name.trim(), phone.trim() || undefined);
      if (duplicates.length > 0) {
        const proceed = await new Promise<boolean>((resolve) => {
          Alert.alert(
            "Possible duplicate",
            `A similar store already exists: "${duplicates[0].name}". Add this as a new store anyway?`,
            [
              { text: "Cancel", style: "cancel", onPress: () => resolve(false) },
              { text: "Add anyway", onPress: () => resolve(true) },
            ]
          );
        });
        if (!proceed) {
          setSaving(false);
          return;
        }
      }

      const store: MedicalStore = {
        id: generateUuid(),
        name: name.trim(),
        contactName: contactName.trim() || null,
        phone: phone.trim() || null,
        address: address.trim() || null,
        city: city.trim() || null,
        areaId: selectedAreaId,
        active: true,
      };

      const net = await NetInfo.fetch();
      const online = !!net.isConnected && net.isInternetReachable !== false;

      if (online) {
        try {
          const created = await api.post<MedicalStore>("/stores", { ...store, clientId: store.id });
          await insertLocalStore(created, "SYNCED");
        } catch {
          await insertLocalStore(store, "PENDING_SYNC");
        }
      } else {
        await insertLocalStore(store, "PENDING_SYNC");
      }

      runSync();
      navigation.goBack();
    } finally {
      setSaving(false);
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <ScrollView contentContainerStyle={{ padding: 16 }}>
        <Text style={styles.label}>Medical Store Name *</Text>
        <TextInput style={styles.input} value={name} onChangeText={setName} placeholder="e.g. City Pharmacy" />
        {selectedAreaName ? <Text style={styles.areaNote}>This store will be linked to {selectedAreaName}</Text> : null}

        <Text style={styles.label}>Owner Name</Text>
        <TextInput style={styles.input} value={contactName} onChangeText={setContactName} />

        <Text style={styles.label}>Phone</Text>
        <TextInput style={styles.input} value={phone} onChangeText={setPhone} keyboardType="phone-pad" />

        <Text style={styles.label}>Address</Text>
        <TextInput style={styles.input} value={address} onChangeText={setAddress} />

        <Text style={styles.label}>City / Area</Text>
        <TextInput style={styles.input} value={city} onChangeText={setCity} />

        <Pressable style={styles.saveButton} onPress={saveStore} disabled={saving}>
          <Text style={styles.saveButtonText}>{saving ? "Saving…" : "Save Store"}</Text>
        </Pressable>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff" },
  label: { fontSize: 13, color: "#555", marginTop: 12, marginBottom: 4, fontWeight: "600" },
  areaNote: { fontSize: 12, color: "#1a3d7c", marginTop: 4 },
  input: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, paddingHorizontal: 12, paddingVertical: 10 },
  saveButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 14, alignItems: "center", marginTop: 24 },
  saveButtonText: { color: "#fff", fontWeight: "600", fontSize: 15 },
});
