import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { router } from 'expo-router';
import { api } from '../../services/api';

export default function CompanyCodeScreen() {
  const [slug, setSlug] = useState('');
  const [loading, setLoading] = useState(false);

  const handleContinue = async () => {
    if (!slug.trim()) return Alert.alert('Required', 'Please enter your company code.');
    setLoading(true);
    try {
      const res = await api.get(`/api/v1/auth/tenant/${slug.trim().toLowerCase()}/exists`);
      if (res.data?.exists) {
        router.push({ pathname: '/(auth)/login', params: { tenantSlug: slug.trim().toLowerCase() } });
      } else {
        Alert.alert('Not Found', 'Company code not found. Please check and try again.');
      }
    } catch {
      Alert.alert('Error', 'Could not verify company code. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView
      className="flex-1 bg-white"
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View className="flex-1 justify-center px-8">
        <View className="mb-10 items-center">
          <View className="w-16 h-16 rounded-2xl bg-primary items-center justify-center mb-4">
            <Text className="text-white text-3xl font-bold">F</Text>
          </View>
          <Text className="text-3xl font-bold text-gray-900">FiberOps</Text>
          <Text className="text-gray-500 mt-1">Field Operations</Text>
        </View>

        <Text className="text-xl font-semibold text-gray-900 mb-2">Enter Company Code</Text>
        <Text className="text-gray-500 mb-6">Ask your admin for your company's unique code.</Text>

        <TextInput
          className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-4"
          placeholder="e.g. mybusiness"
          value={slug}
          onChangeText={setSlug}
          autoCapitalize="none"
          autoCorrect={false}
          autoFocus
        />

        <TouchableOpacity
          className="bg-primary rounded-xl py-4 items-center"
          onPress={handleContinue}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text className="text-white font-semibold text-base">Continue</Text>
          )}
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
}
