import { useState } from 'react';
import {
  KeyboardAvoidingView,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { requestCode, verifyCode, type CodeRequest } from './api';
import type { User } from './types';
import { Button, Card, Field, Notice, uiStyles } from './ui';
import { colors } from './theme';

type AuthMode = 'login' | 'register' | 'link';

interface AuthScreenProps {
  initialNotice?: string;
  initialRole?: 'customer' | 'contractor';
  onCancel: () => void;
  onAuthenticated: (token: string, user: User) => Promise<void>;
}

const modeCopy: Record<AuthMode, { title: string; subtitle: string; button: string }> = {
  login: {
    title: 'Welcome back',
    subtitle: 'Sign in securely with a WhatsApp verification code.',
    button: 'Send WhatsApp code',
  },
  register: {
    title: 'Create your account',
    subtitle: 'Set up a customer or contractor account using your WhatsApp number.',
    button: 'Create account and send code',
  },
  link: {
    title: 'Link an existing account',
    subtitle: 'Verify your password once, then connect a WhatsApp number to your account.',
    button: 'Verify account and send code',
  },
};

export default function AuthScreen({ initialNotice, initialRole, onCancel, onAuthenticated }: AuthScreenProps) {
  const [mode, setMode] = useState<AuthMode>('login');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [phone, setPhone] = useState('');
  const [role, setRole] = useState<'customer' | 'contractor'>(initialRole || 'customer');
  const [city, setCity] = useState('');
  const [parish, setParish] = useState('');
  const [businessName, setBusinessName] = useState('');
  const [challengeId, setChallengeId] = useState<number | null>(null);
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(initialNotice || '');

  function chooseMode(nextMode: AuthMode) {
    setMode(nextMode);
    setChallengeId(null);
    setCode('');
    setError('');
    setSuccess('');
  }

  async function sendCode() {
    setBusy(true);
    setError('');
    setSuccess('');
    try {
      const request: CodeRequest = {
        purpose: mode,
        phone: phone.trim(),
      };
      if (mode === 'register') {
        Object.assign(request, {
          name: name.trim(),
          email: email.trim(),
          role,
          city: city.trim(),
          parish: parish.trim(),
          business_name: businessName.trim(),
        });
      } else if (mode === 'link') {
        Object.assign(request, {
          email: email.trim(),
          password,
        });
      }
      const response = await requestCode(request);
      setChallengeId(response.challenge_id);
      setSuccess(response.message);
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : 'Could not request a verification code.');
    } finally {
      setBusy(false);
    }
  }

  async function confirmCode() {
    if (challengeId === null) {
      return;
    }
    setBusy(true);
    setError('');
    try {
      const response = await verifyCode(challengeId, code.trim());
      await onAuthenticated(response.token, response.user);
    } catch (verifyError) {
      setError(verifyError instanceof Error ? verifyError.message : 'Could not verify the code.');
    } finally {
      setBusy(false);
    }
  }

  const copy = modeCopy[mode];

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      style={uiStyles.page}
    >
      <SafeAreaView style={uiStyles.page}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <Pressable accessibilityRole="button" onPress={onCancel} style={styles.backButton}>
          <Text style={styles.backText}>‹ Back to home</Text>
        </Pressable>
        <View style={styles.brandMark}>
          <Text style={styles.brandLetter}>J</Text>
        </View>
        <Text style={styles.brandName}>JaforLife</Text>
        <Text style={styles.brandTagline}>Trusted help, closer to home.</Text>

        <Card style={styles.authCard}>
          <Text style={uiStyles.heading}>{challengeId ? 'Verify your number' : copy.title}</Text>
          <Text style={[uiStyles.subheading, styles.subtitle]}>
            {challengeId
              ? `Enter the 6-digit code sent to ${phone}.`
              : copy.subtitle}
          </Text>

          {error ? <Notice message={error} /> : null}
          {success ? <Notice kind="success" message={success} /> : null}

          {!challengeId ? (
            <>
              <View style={styles.modePicker}>
                {([
                  ['login', 'Sign in'],
                  ['register', 'Create account'],
                  ['link', 'Link account'],
                ] as const).map(([value, label]) => (
                  <Pressable
                    accessibilityRole="tab"
                    accessibilityState={{ selected: mode === value }}
                    key={value}
                    onPress={() => chooseMode(value)}
                    style={[styles.modeButton, mode === value && styles.modeButtonActive]}
                  >
                    <Text style={[styles.modeText, mode === value && styles.modeTextActive]}>{label}</Text>
                  </Pressable>
                ))}
              </View>

              {mode === 'register' ? (
                <>
                  <Field label="Your name" value={name} onChangeText={setName} placeholder="Full name" autoComplete="name" />
                  <Text style={styles.fieldLabel}>I am joining as a</Text>
                  <View style={styles.roleRow}>
                    {(['customer', 'contractor'] as const).map((value) => (
                      <Pressable
                        key={value}
                        onPress={() => setRole(value)}
                        style={[styles.roleOption, role === value && styles.roleOptionActive]}
                      >
                        <Text style={[styles.roleOptionText, role === value && styles.roleOptionTextActive]}>
                          {value === 'customer' ? 'Customer' : 'Contractor'}
                        </Text>
                      </Pressable>
                    ))}
                  </View>
                  <Field label="Email (optional)" value={email} onChangeText={setEmail} placeholder="you@example.com" keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
                  <Field label="City" value={city} onChangeText={setCity} placeholder="Your city" />
                  <Field label="Parish" value={parish} onChangeText={setParish} placeholder="Your parish" />
                  {role === 'contractor' ? (
                    <Field label="Business name (optional)" value={businessName} onChangeText={setBusinessName} placeholder="Business or trading name" />
                  ) : null}
                </>
              ) : null}

              {mode === 'link' ? (
                <>
                  <Field label="Account email" value={email} onChangeText={setEmail} placeholder="Email on your existing account" keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
                  <Field label="Current password" value={password} onChangeText={setPassword} placeholder="Password" secureTextEntry autoComplete="current-password" />
                </>
              ) : null}

              <Field
                label="WhatsApp number"
                value={phone}
                onChangeText={setPhone}
                placeholder="+18765551234"
                keyboardType="phone-pad"
                autoCapitalize="none"
                autoComplete="tel"
              />
              <Text style={styles.helper}>
                Use the full international format including country code, for example +1 876 555 1234.
              </Text>
              <Button
                title={busy ? 'Please wait...' : copy.button}
                onPress={() => void sendCode()}
                disabled={busy}
              />
            </>
          ) : (
            <>
              <Field
                label="6-digit verification code"
                value={code}
                onChangeText={setCode}
                placeholder="000000"
                keyboardType="number-pad"
                autoCapitalize="none"
                maxLength={6}
              />
              <Button
                title={busy ? 'Verifying...' : 'Verify and sign in'}
                onPress={() => void confirmCode()}
                disabled={busy || code.trim().length !== 6}
              />
              <View style={uiStyles.gap} />
              <Button
                title="Use a different number"
                onPress={() => {
                  setChallengeId(null);
                  setCode('');
                  setSuccess('');
                  setError('');
                }}
                variant="secondary"
                disabled={busy}
              />
            </>
          )}
        </Card>
        <Text style={styles.footer}>WhatsApp verification codes are sent by the JaforLife service.</Text>
      </ScrollView>
      </SafeAreaView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  content: {
    flexGrow: 1,
    justifyContent: 'center',
    padding: 22,
    paddingBottom: 32,
  },
  backButton: {
    alignSelf: 'flex-start',
    marginBottom: 14,
    paddingVertical: 8,
  },
  backText: {
    color: colors.primaryDark,
    fontSize: 14,
    fontWeight: '700',
  },
  brandMark: {
    alignItems: 'center',
    alignSelf: 'center',
    backgroundColor: colors.primary,
    borderRadius: 20,
    height: 58,
    justifyContent: 'center',
    marginBottom: 10,
    width: 58,
  },
  brandLetter: {
    color: colors.surface,
    fontSize: 30,
    fontWeight: '900',
  },
  brandName: {
    color: colors.navy,
    fontSize: 27,
    fontWeight: '900',
    textAlign: 'center',
  },
  brandTagline: {
    color: colors.muted,
    fontSize: 14,
    marginBottom: 22,
    marginTop: 4,
    textAlign: 'center',
  },
  authCard: {
    padding: 19,
  },
  subtitle: {
    marginBottom: 18,
  },
  modePicker: {
    backgroundColor: colors.canvas,
    borderRadius: 13,
    flexDirection: 'row',
    marginBottom: 18,
    padding: 4,
  },
  modeButton: {
    alignItems: 'center',
    borderRadius: 10,
    flex: 1,
    justifyContent: 'center',
    minHeight: 40,
    paddingHorizontal: 5,
  },
  modeButtonActive: {
    backgroundColor: colors.surface,
    elevation: 1,
  },
  modeText: {
    color: colors.muted,
    fontSize: 12,
    fontWeight: '700',
  },
  modeTextActive: {
    color: colors.primaryDark,
  },
  fieldLabel: {
    color: colors.ink,
    fontSize: 13,
    fontWeight: '700',
    marginBottom: 7,
  },
  roleRow: {
    flexDirection: 'row',
    gap: 10,
    marginBottom: 14,
  },
  roleOption: {
    alignItems: 'center',
    backgroundColor: colors.canvas,
    borderColor: colors.border,
    borderRadius: 12,
    borderWidth: 1,
    flex: 1,
    justifyContent: 'center',
    minHeight: 45,
  },
  roleOptionActive: {
    backgroundColor: colors.primarySoft,
    borderColor: colors.primary,
  },
  roleOptionText: {
    color: colors.muted,
    fontSize: 14,
    fontWeight: '700',
  },
  roleOptionTextActive: {
    color: colors.primaryDark,
  },
  helper: {
    color: colors.muted,
    fontSize: 12,
    lineHeight: 18,
    marginBottom: 14,
    marginTop: -7,
  },
  footer: {
    color: colors.muted,
    fontSize: 11,
    lineHeight: 17,
    marginTop: 18,
    textAlign: 'center',
  },
});
