import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
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. Please try again.');
    } finally { setLoading(false); }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#FFF' }}>
      <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
        <View style={{ flex: 1, justifyContent: 'center', paddingHorizontal: 24 }}>
          {/* Logo */}
          <View style={{ alignItems: 'center', marginBottom: 48 }}>
            <View style={{ width: 84, height: 84, borderRadius: 24, backgroundColor: '#0891B2', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
              <Text style={{ color: '#FFF', fontSize: 40, fontWeight: '900' }}>F</Text>
            </View>
            <Text style={{ fontSize: 32, fontWeight: '900', color: '#0F172A', letterSpacing: -0.5 }}>FiberOps</Text>
            <Text style={{ fontSize: 16, color: '#94A3B8', marginTop: 4 }}>Field Operations Platform</Text>
          </View>

          <Text style={{ fontSize: 22, fontWeight: '800', color: '#0F172A', marginBottom: 6 }}>Enter Company Code</Text>
          <Text style={{ fontSize: 16, color: '#64748B', marginBottom: 20, lineHeight: 22 }}>Ask your admin for your company's unique code.</Text>

          <TextInput
            style={{ backgroundColor: '#F8FAFC', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 18, paddingVertical: 16, fontSize: 17, color: '#0F172A', marginBottom: 16 }}
            placeholder="e.g. demo-isp"
            placeholderTextColor="#94A3B8"
            value={slug}
            onChangeText={setSlug}
            autoCapitalize="none"
            autoCorrect={false}
            autoFocus
            onSubmitEditing={handleContinue}
          />

          <TouchableOpacity
            style={{ backgroundColor: '#0891B2', borderRadius: 14, paddingVertical: 18, alignItems: 'center' }}
            onPress={handleContinue}
            disabled={loading}
            activeOpacity={0.8}
          >
            {loading
              ? <ActivityIndicator color="#FFF" />
              : <Text style={{ color: '#FFF', fontSize: 17, fontWeight: '700' }}>Continue →</Text>
            }
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
