import { Modal, Text, TouchableOpacity, View, Vibration } from 'react-native';
import { useEffect, useMemo, useState } from 'react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import { apiFetch, API_URL } from '../services/api';
import styles from '../styles/index';

export function PinLockScreen() {
  const { staffList, themeColor } = useApp();
  const { currentUser, handleSessionExpired, showLogin, setShowLogin, securityMode, applyAuthSession } = useAuth();
  
  const [selectedStaff, setSelectedStaff] = useState(null);
  const [enteredPin, setEnteredPin] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const pinStaff = useMemo(
    () => staffList.filter(s => s.is_active && s.role !== 'master' && (s.has_pin || !!s.pin_code)),
    [staffList]
  );

  useEffect(() => {
    if (
      showLogin &&
      securityMode === 'individual_pin' &&
      currentUser?.role === 'master' &&
      staffList.length > 0
    ) {
      setShowLogin(false);
    }
  }, [currentUser?.role, pinStaff.length, securityMode, setShowLogin, showLogin, staffList.length]);

  const handleStaffSelect = (staff) => {
    setSelectedStaff(staff);
    setEnteredPin('');
    setError('');
  };

  const handlePinPress = (digit) => {
    if (enteredPin.length < 4) {
      setEnteredPin(prev => prev + digit);
      setError('');
    }
  };

  const handlePinDelete = () => {
    setEnteredPin(prev => prev.slice(0, -1));
    setError('');
  };

  const handlePinClear = () => {
    setEnteredPin('');
    setError('');
  };

  const handleBackToRoster = () => {
    setSelectedStaff(null);
    setEnteredPin('');
    setError('');
  };

  const handlePinSubmit = async () => {
    if (enteredPin.length !== 4) {
      setError('Please enter a 4-digit PIN');
      Vibration.vibrate(100);
      return;
    }

    if (!selectedStaff) {
      setError('Please select a staff member');
      Vibration.vibrate(100);
      return;
    }

    setIsLoading(true);
    setError('');

    try {
      const res = await apiFetch(API_URL, {
        method: 'POST',
        body: JSON.stringify({
          action: 'verify_pin_login',
          staff_id: selectedStaff.id,
          pin_code: enteredPin,
        }),
      });

      const data = await res.json();

      if (!data.success) {
        setError(data.error || 'Invalid PIN');
        setEnteredPin('');
        Vibration.vibrate([100, 100, 100]);
        setIsLoading(false);
        return;
      }

      await applyAuthSession(data);
      setShowLogin(false);
      setSelectedStaff(null);
      setEnteredPin('');
      Vibration.vibrate(50);
    } catch (_e) {
      setError('Connection error. Please try again.');
      setEnteredPin('');
      Vibration.vibrate([100, 100, 100]);
    } finally {
      setIsLoading(false);
    }
  };

  if (!showLogin || securityMode !== 'individual_pin') return null;
  if (currentUser?.role === 'master') return null;

  return (
    <Modal visible={showLogin} transparent animationType="fade">
      <View style={styles.modalOverlay}>
        <View style={[styles.modalContent, { maxWidth: 400, width: '90%' }]}>
          
          {!selectedStaff ? (
            // State 1: Employee Roster
            <View>
              <Text style={{ fontSize: 22, fontWeight: 'bold', marginBottom: 10, textAlign: 'center' }}>
                Who is packing?
              </Text>
              <Text style={{ fontSize: 13, color: '#666', marginBottom: 20, textAlign: 'center' }}>
                Select your name to continue
              </Text>

              <View style={styles.rosterGrid}>
                {pinStaff.map(s => (
                  <TouchableOpacity
                    key={s.id}
                    style={[styles.rosterBtn, { backgroundColor: themeColor }]}
                    onPress={() => handleStaffSelect(s)}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>{s.name}</Text>
                  </TouchableOpacity>
                ))}
                {pinStaff.length === 0 ? (
                  <View style={{ width: '100%', alignItems: 'center' }}>
                    <Text style={{ color: '#999', textAlign: 'center', marginBottom: 12 }}>
                      No staff PINs have been set up yet. Please ask the master admin to sign in and assign PINs in Settings.
                    </Text>
                    <TouchableOpacity style={[styles.packBtn, { backgroundColor: themeColor }]} onPress={handleSessionExpired}>
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>ADMIN LOGIN</Text>
                    </TouchableOpacity>
                  </View>
                ) : null}
              </View>
            </View>
          ) : (
            // State 2: Numeric Keypad
            <View>
              <TouchableOpacity
                style={{ alignSelf: 'flex-start', marginBottom: 10 }}
                onPress={handleBackToRoster}
              >
                <Text style={{ color: '#666', fontSize: 14 }}>← Back</Text>
              </TouchableOpacity>

              <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 5, textAlign: 'center' }}>
                {selectedStaff.name}
              </Text>
              <Text style={{ fontSize: 13, color: '#666', marginBottom: 20, textAlign: 'center' }}>
                Enter your 4-digit PIN
              </Text>

              {/* PIN Display */}
              <View style={{ flexDirection: 'row', justifyContent: 'center', gap: 12, marginBottom: 30 }}>
                {[0, 1, 2, 3].map(i => (
                  <View
                    key={i}
                    style={{
                      width: 50,
                      height: 50,
                      borderRadius: 25,
                      borderWidth: 2,
                      borderColor: enteredPin.length > i ? themeColor : '#ccc',
                      backgroundColor: enteredPin.length > i ? themeColor : '#fff',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <Text style={{ fontSize: 24, fontWeight: 'bold', color: enteredPin.length > i ? '#fff' : '#ccc' }}>
                      {enteredPin[i] ? '•' : ''}
                    </Text>
                  </View>
                ))}
              </View>

              {error ? (
                <Text style={{ color: '#e74c3c', textAlign: 'center', marginBottom: 15, fontWeight: '600' }}>
                  {error}
                </Text>
              ) : null}

              {/* Numeric Keypad */}
              <View style={{ gap: 12 }}>
                {[1, 2, 3].map(num => (
                  <View key={num} style={{ flexDirection: 'row', gap: 12 }}>
                    {[num, num + 3, num + 6].map(digit => (
                      <TouchableOpacity
                        key={digit}
                        style={{
                          flex: 1,
                          height: 60,
                          borderRadius: 12,
                          backgroundColor: '#f5f5f5',
                          alignItems: 'center',
                          justifyContent: 'center',
                          borderWidth: 1,
                          borderColor: '#e0e0e0',
                        }}
                        onPress={() => handlePinPress(digit.toString())}
                        disabled={isLoading}
                      >
                        <Text style={{ fontSize: 24, fontWeight: '600', color: '#333' }}>{digit}</Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                ))}

                <View style={{ flexDirection: 'row', gap: 12 }}>
                  <TouchableOpacity
                    style={{
                      flex: 1,
                      height: 60,
                      borderRadius: 12,
                      backgroundColor: '#f5f5f5',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderWidth: 1,
                      borderColor: '#e0e0e0',
                    }}
                    onPress={handlePinClear}
                    disabled={isLoading}
                  >
                    <Text style={{ fontSize: 16, fontWeight: '600', color: '#666' }}>Clear</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={{
                      flex: 1,
                      height: 60,
                      borderRadius: 12,
                      backgroundColor: '#f5f5f5',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderWidth: 1,
                      borderColor: '#e0e0e0',
                    }}
                    onPress={() => handlePinPress('0')}
                    disabled={isLoading}
                  >
                    <Text style={{ fontSize: 24, fontWeight: '600', color: '#333' }}>0</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={{
                      flex: 1,
                      height: 60,
                      borderRadius: 12,
                      backgroundColor: '#ffebee',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderWidth: 1,
                      borderColor: '#ffcdd2',
                    }}
                    onPress={handlePinDelete}
                    disabled={isLoading}
                  >
                    <Text style={{ fontSize: 20, fontWeight: '600', color: '#c62828' }}>⌫</Text>
                  </TouchableOpacity>
                </View>

                {enteredPin.length === 4 && (
                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: themeColor, height: 60, marginTop: 8 }]}
                    onPress={handlePinSubmit}
                    disabled={isLoading}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>
                      {isLoading ? 'Verifying...' : 'UNLOCK'}
                    </Text>
                  </TouchableOpacity>
                )}
              </View>
            </View>
          )}
        </View>
      </View>
    </Modal>
  );
}
