import { Modal, ScrollView, StatusBar, Switch, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useAuth } from '../context/AuthContext';
import styles from '../styles/index';

export function OnboardingScreen() {
  const {
    appScreen,
    obLogin,
    setObLogin,
    obSetup,
    setObSetup,
    obLoading,
    obError,
    setObError,
    onboardStep,
    setOnboardStep,
    handleObLogin,
    handleVerifyClient,
    handleObSetup,
  } = useAuth();

  return (
    <Modal visible={appScreen !== 'app'} animationType="none">
      <View style={styles.obContainer}>
        <StatusBar barStyle="light-content" backgroundColor="#007a58" />

        {/* Loading splash */}
        {appScreen === 'loading' && (
          <View style={styles.obCenter}>
            <Text style={styles.obLogo}>📦</Text>
            <Text style={styles.obAppName}>Warehouse</Text>
          </View>
        )}

        {/* LAUNCH */}
        {appScreen === 'onboarding' && onboardStep === 'launch' && (
          <View style={styles.obCenter}>
            <Text style={styles.obLogo}>📦</Text>
            <Text style={styles.obAppName}>Warehouse Manager</Text>
            <Text style={styles.obTagline}>Pick · Pack · Ship</Text>
            <View style={{ width: '100%', marginTop: 50 }}>
              <TouchableOpacity
                style={styles.obBtnPrimary}
                onPress={() => { setObError(''); setOnboardStep('login'); }}
              >
                <Text style={styles.obBtnPrimaryText}>LOG IN TO EXISTING COMPANY</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.obBtnSecondary}
                onPress={() => { setObError(''); setOnboardStep('verify'); }}
              >
                <Text style={styles.obBtnSecondaryText}>SET UP NEW COMPANY</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {/* VERIFY (master registry gate) */}
        {appScreen === 'onboarding' && onboardStep === 'verify' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('launch'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Verify Your Business</Text>
            <Text style={styles.obStepSub}>
              Enter the business slug and setup key for this PickPack Ship install.
            </Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Business Slug</Text>
            <TextInput
              style={styles.obInput}
              placeholder="pickpack"
              autoCapitalize="none"
              autoCorrect={false}
              value={obSetup.businessSlug}
              onChangeText={t => setObSetup({ ...obSetup, businessSlug: t.toLowerCase().replace(/[^a-z0-9\-_]/g, '') })}
            />

            <Text style={styles.obLabel}>Setup Key</Text>
            <TextInput
              style={styles.obInput}
              placeholder="Key provided by Afrihair"
              autoCapitalize="none"
              autoCorrect={false}
              secureTextEntry
              value={obSetup.clientKey}
              onChangeText={t => setObSetup({ ...obSetup, clientKey: t })}
            />

            <TouchableOpacity
              style={[styles.obBtnPrimary, obLoading && { backgroundColor: '#b0d4c8' }]}
              onPress={handleVerifyClient}
              disabled={obLoading}
            >
              <Text style={styles.obBtnPrimaryText}>{obLoading ? 'VERIFYING...' : 'VERIFY & CONTINUE →'}</Text>
            </TouchableOpacity>
          </ScrollView>
        )}

        {/* LOGIN */}
        {appScreen === 'onboarding' && onboardStep === 'login' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('launch'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Log In</Text>
            <Text style={styles.obStepSub}>Enter your company ID, choose role, and password.</Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Company ID</Text>
            <TextInput
              style={styles.obInput}
              placeholder="pickpack"
              autoCapitalize="none"
              autoCorrect={false}
              value={obLogin.company}
              onChangeText={t => setObLogin({ ...obLogin, company: t.toLowerCase().trim() })}
            />

            <Text style={styles.obLabel}>Role</Text>
            <View style={{ flexDirection: 'row', gap: 10, marginBottom: 18 }}>
              <TouchableOpacity
                style={[styles.obChip, obLogin.role === 'admin' && styles.obChipActive]}
                onPress={() => setObLogin({ ...obLogin, role: 'admin' })}
              >
                <Text style={[styles.obChipText, obLogin.role === 'admin' && styles.obChipTextActive]}>Admin</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.obChip, obLogin.role !== 'admin' && styles.obChipActive]}
                onPress={() => setObLogin({ ...obLogin, role: 'user' })}
              >
                <Text style={[styles.obChipText, obLogin.role !== 'admin' && styles.obChipTextActive]}>User</Text>
              </TouchableOpacity>
            </View>

            <Text style={styles.obLabel}>Password</Text>
            <TextInput
              style={styles.obInput}
              placeholder="Your password"
              secureTextEntry
              value={obLogin.password}
              onChangeText={t => setObLogin({ ...obLogin, password: t })}
            />

            <View style={styles.obToggleRow}>
              <Text style={{ flex: 1, fontSize: 15, color: '#fff' }}>Keep me logged in</Text>
              <Switch value={obLogin.saveMe} onValueChange={v => setObLogin({ ...obLogin, saveMe: v })} />
            </View>

            <TouchableOpacity
              style={[styles.obBtnPrimary, obLoading && { backgroundColor: '#b0d4c8' }]}
              onPress={() => handleObLogin()}
              disabled={obLoading}
            >
              <Text style={styles.obBtnPrimaryText}>{obLoading ? 'LOGGING IN...' : 'LOG IN'}</Text>
            </TouchableOpacity>
          </ScrollView>
        )}

        {/* SETUP STEP 1 — COMPANY */}
        {appScreen === 'onboarding' && onboardStep === 'setup_company' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('verify'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Step 1 of 4 — Company</Text>
            <Text style={styles.obStepSub}>
              Create your warehouse company. Multiple devices can connect to the same company.
            </Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Company Display Name</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. Afrihair NZ"
              value={obSetup.companyName}
              onChangeText={t => setObSetup({ ...obSetup, companyName: t })}
            />

            <Text style={styles.obLabel}>
              Company ID{' '}
              <Text style={{ color: 'rgba(255,255,255,0.6)', fontWeight: 'normal', fontSize: 11 }}>(assigned by registry)</Text>
            </Text>
            <View style={[styles.obInput, { justifyContent: 'center', opacity: 0.6 }]}>
              <Text style={{ color: '#fff', fontSize: 15 }}>{obSetup.companySlug}</Text>
            </View>

            <TouchableOpacity
              style={styles.obBtnPrimary}
              onPress={() => {
                if (!obSetup.companyName.trim() || !obSetup.companySlug.trim()) return setObError('Company name is required.');
                setObError(''); setOnboardStep('setup_account');
              }}
            >
              <Text style={styles.obBtnPrimaryText}>NEXT →</Text>
            </TouchableOpacity>
          </ScrollView>
        )}

        {/* SETUP STEP 2 — MASTER ACCOUNT */}
        {appScreen === 'onboarding' && onboardStep === 'setup_account' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('setup_company'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Step 2 of 4 — Master Account</Text>
            <Text style={styles.obStepSub}>
              This account has full access including setup and staff management.
            </Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Your Display Name</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. Daniel"
              value={obSetup.displayName}
              onChangeText={t => setObSetup({ ...obSetup, displayName: t })}
            />

            <Text style={styles.obLabel}>Username</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. daniel"
              autoCapitalize="none"
              autoCorrect={false}
              value={obSetup.username}
              onChangeText={t => setObSetup({ ...obSetup, username: t.trim() })}
            />

            <Text style={styles.obLabel}>
              Password{' '}
              <Text style={{ color: 'rgba(255,255,255,0.6)', fontWeight: 'normal', fontSize: 11 }}>(min. 8 characters)</Text>
            </Text>
            <TextInput
              style={styles.obInput}
              placeholder="Choose a strong password"
              secureTextEntry
              value={obSetup.password}
              onChangeText={t => setObSetup({ ...obSetup, password: t })}
            />

            <Text style={styles.obLabel}>Confirm Password</Text>
            <TextInput
              style={styles.obInput}
              placeholder="Repeat password"
              secureTextEntry
              value={obSetup.confirmPassword}
              onChangeText={t => setObSetup({ ...obSetup, confirmPassword: t })}
            />

            <TouchableOpacity
              style={styles.obBtnPrimary}
              onPress={() => {
                if (!obSetup.username.trim() || obSetup.password.length < 8)
                  return setObError('Username required. Password min 8 characters.');
                if (obSetup.password !== obSetup.confirmPassword)
                  return setObError('Passwords do not match.');
                setObError(''); setOnboardStep('setup_ecom');
              }}
            >
              <Text style={styles.obBtnPrimaryText}>NEXT →</Text>
            </TouchableOpacity>
          </ScrollView>
        )}

        {/* SETUP STEP 3 — ECOMMERCE */}
        {appScreen === 'onboarding' && onboardStep === 'setup_ecom' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('setup_account'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Step 3 of 4 — Ecommerce</Text>
            <Text style={styles.obStepSub}>Connect an online store now, or skip this and use courier orders only.</Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Platform</Text>
            <View style={{ flexDirection: 'row', gap: 10, marginBottom: 18 }}>
              {[['none', 'None'], ['shopify', 'Shopify']].map(([val, label]) => (
                <TouchableOpacity
                  key={val}
                  style={[styles.obChip, obSetup.ecomProvider === val && styles.obChipActive]}
                  onPress={() => setObSetup({
                    ...obSetup,
                    ecomProvider: val,
                    ...(val === 'none' ? { ecomStoreUrl: '', ecomApiKey: '' } : {}),
                  })}
                >
                  <Text style={[styles.obChipText, obSetup.ecomProvider === val && styles.obChipTextActive]}>{label}</Text>
                </TouchableOpacity>
              ))}
            </View>

            {obSetup.ecomProvider !== 'none' && (
              <>
                <Text style={styles.obLabel}>Store URL</Text>
                <TextInput
                  style={styles.obInput}
                  placeholder="yourstore.myshopify.com"
                  autoCapitalize="none"
                  autoCorrect={false}
                  keyboardType="url"
                  value={obSetup.ecomStoreUrl}
                  onChangeText={t => setObSetup({ ...obSetup, ecomStoreUrl: t.trim() })}
                />

                <Text style={styles.obLabel}>
                  Admin API Access Token
                </Text>
                <TextInput
                  style={styles.obInput}
                  placeholder="shpat_..."
                  autoCapitalize="none"
                  autoCorrect={false}
                  secureTextEntry
                  value={obSetup.ecomApiKey}
                  onChangeText={t => setObSetup({ ...obSetup, ecomApiKey: t.trim() })}
                />
              </>
            )}

            <TouchableOpacity
              style={styles.obBtnPrimary}
              onPress={() => {
                if (obSetup.ecomProvider !== 'none' && (!obSetup.ecomStoreUrl.trim() || !obSetup.ecomApiKey.trim()))
                  return setObError('Store URL and API key are required.');
                setObError(''); setOnboardStep('setup_shipping');
              }}
            >
              <Text style={styles.obBtnPrimaryText}>NEXT →</Text>
            </TouchableOpacity>
          </ScrollView>
        )}

        {/* SETUP STEP 4 — SHIPPING */}
        {appScreen === 'onboarding' && onboardStep === 'setup_shipping' && (
          <ScrollView contentContainerStyle={styles.obScrollContent} keyboardShouldPersistTaps="handled">
            <TouchableOpacity style={styles.obBackBtn} onPress={() => { setObError(''); setOnboardStep('setup_ecom'); }}>
              <Text style={styles.obBackText}>← Back</Text>
            </TouchableOpacity>
            <Text style={styles.obStepTitle}>Step 4 of 4 — Shipping</Text>
            <Text style={styles.obStepSub}>
              Connect your shipping provider and set your warehouse send-from address.
            </Text>
            {obError ? (
              <View style={styles.obErrorBox}>
                <Text style={styles.obErrorText}>{obError}</Text>
              </View>
            ) : null}

            <Text style={styles.obLabel}>Provider</Text>
            <View style={{ flexDirection: 'row', gap: 10, marginBottom: 18 }}>
              {[['packie', 'Packie'], ['zappy', 'Zappy']].map(([val, label]) => (
                <TouchableOpacity
                  key={val}
                  style={[styles.obChip, obSetup.shipProvider === val && styles.obChipActive]}
                  onPress={() => setObSetup({ ...obSetup, shipProvider: val })}
                >
                  <Text style={[styles.obChipText, obSetup.shipProvider === val && styles.obChipTextActive]}>{label}</Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.obLabel}>Shipping Username</Text>
            <TextInput
              style={styles.obInput}
              placeholder="Your account username"
              autoCapitalize="none"
              autoCorrect={false}
              value={obSetup.shipUsername}
              onChangeText={t => setObSetup({ ...obSetup, shipUsername: t })}
            />

            <Text style={styles.obLabel}>Shipping Password / API Key</Text>
            <TextInput
              style={styles.obInput}
              placeholder="Password or API key"
              autoCapitalize="none"
              secureTextEntry
              value={obSetup.shipApiKey}
              onChangeText={t => setObSetup({ ...obSetup, shipApiKey: t })}
            />

            <View style={styles.obDivider} />
            <Text style={[styles.obLabel, { fontSize: 13, color: 'rgba(255,255,255,0.9)', marginBottom: 14 }]}>
              📍 WAREHOUSE SEND-FROM ADDRESS
            </Text>

            <Text style={styles.obLabel}>Contact Name</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. Daniel Smith"
              value={obSetup.senderName}
              onChangeText={t => setObSetup({ ...obSetup, senderName: t })}
            />

            <Text style={styles.obLabel}>Street Address</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. 247 Cuba Street"
              value={obSetup.senderStreet}
              onChangeText={t => setObSetup({ ...obSetup, senderStreet: t })}
            />

            <Text style={styles.obLabel}>City</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. Palmerston North"
              value={obSetup.senderCity}
              onChangeText={t => setObSetup({ ...obSetup, senderCity: t })}
            />

            <Text style={styles.obLabel}>Postcode</Text>
            <TextInput
              style={styles.obInput}
              placeholder="e.g. 4410"
              keyboardType="numeric"
              value={obSetup.senderPostcode}
              onChangeText={t => setObSetup({ ...obSetup, senderPostcode: t })}
            />

            <TouchableOpacity
              style={[styles.obBtnPrimary, obLoading && { backgroundColor: '#b0d4c8' }]}
              onPress={handleObSetup}
              disabled={obLoading}
            >
              <Text style={styles.obBtnPrimaryText}>{obLoading ? 'SETTING UP...' : '✓ COMPLETE SETUP'}</Text>
            </TouchableOpacity>
          </ScrollView>
        )}
      </View>
    </Modal>
  );
}
