import { useEffect, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import api, { getApiBaseUrl } from '../../core/api';
import { captchaPayload, isCaptchaReady, type CaptchaState } from '../../core/captcha';
import { extractApiError } from '../../core/getApiBaseUrl';
import { useAuth } from '../../context/AuthContext';
import { GuestStackParamList } from '../../navigation/types';
import { ScreenLayout } from '../../components/ui/ScreenLayout';
import { FormField } from '../../components/ui/FormField';
import { AppButton } from '../../components/ui/AppButton';
import { Icon } from '../../components/ui/Icon';
import { CaptchaField } from '../../components/auth/CaptchaField';
import { colors, spacing } from '../../constants/theme';

type Props = NativeStackScreenProps<GuestStackParamList, 'Login'>;

const portals = ['owner', 'staff', 'doctor', 'customer', 'superadmin'];

export function LoginScreen({ navigation }: Props) {
  const { login } = useAuth();
  const [portal, setPortal] = useState('owner');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [captcha, setCaptcha] = useState<CaptchaState>({});
  const [error, setError] = useState('');
  const [apiStatus, setApiStatus] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    api
      .get('/public/app-config', { params: { context: 'login' } })
      .then(() => setApiStatus(`API connected: ${getApiBaseUrl()}`))
      .catch((e) => setApiStatus(extractApiError(e)));
  }, []);

  const submit = async () => {
    if (!isCaptchaReady(captcha)) {
      setError('Please complete the security check.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const { data } = await api.post('/auth/login', {
        portal,
        email,
        password,
        ...captchaPayload(captcha, 'login'),
      });
      const token = await login(data, portal);
      if (!token) {
        setError('Login succeeded but no token was returned.');
      }
    } catch (e: unknown) {
      setError(extractApiError(e));
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenLayout title="Login" subtitle="Sign in to your Online Clinic portal">
      <Text style={[styles.apiStatus, apiStatus.includes('connected') ? styles.ok : styles.warn]}>
        {apiStatus || `API: ${getApiBaseUrl()}`}
      </Text>
      <View style={styles.portalRow}>
        {portals.map((p) => (
          <Pressable
            key={p}
            style={[styles.portalChip, portal === p && styles.portalActive]}
            onPress={() => setPortal(p)}
          >
            <Icon name="profile" size={16} color={portal === p ? colors.primary : colors.textMuted} />
            <Text style={[styles.portalText, portal === p && styles.portalTextActive]}>{p}</Text>
          </Pressable>
        ))}
      </View>
      <FormField field={{ key: 'email', label: 'Email', type: 'email', required: true }} value={email} onChange={(v) => setEmail(String(v))} />
      <FormField field={{ key: 'password', label: 'Password', type: 'password', required: true }} value={password} onChange={(v) => setPassword(String(v))} />
      <CaptchaField context="login" value={captcha} onChange={setCaptcha} />
      {error ? <Text style={styles.error}>{error}</Text> : null}
      <AppButton label="Sign in" icon="login" loading={loading} onPress={submit} />
      <Text style={styles.hint}>Demo: owner@example.com / password (if seeded)</Text>
      <View style={styles.links}>
        <Pressable onPress={() => navigation.navigate('ForgotPassword')}>
          <Text style={styles.link}>Forgot password?</Text>
        </Pressable>
        <Pressable onPress={() => navigation.navigate('Register')}>
          <Text style={styles.link}>Register clinic account</Text>
        </Pressable>
        <Pressable onPress={() => navigation.navigate('CustomerOnboard')}>
          <Text style={styles.link}>Customer first-time access</Text>
        </Pressable>
      </View>
    </ScreenLayout>
  );
}

const styles = StyleSheet.create({
  apiStatus: { fontSize: 12, marginBottom: spacing.md },
  ok: { color: colors.success },
  warn: { color: colors.danger },
  portalRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm, marginBottom: spacing.md },
  portalChip: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: colors.surface,
    borderWidth: 1,
    borderColor: colors.border,
  },
  portalActive: { borderColor: colors.primary, backgroundColor: colors.primaryLight },
  portalText: { fontSize: 12, color: colors.textMuted, textTransform: 'capitalize' },
  portalTextActive: { color: colors.primaryDark, fontWeight: '600' },
  error: { color: colors.danger, marginBottom: spacing.md },
  hint: { fontSize: 12, color: colors.textMuted, marginBottom: spacing.md, textAlign: 'center' },
  links: { marginTop: spacing.lg, gap: spacing.md },
  link: { color: colors.primary, fontWeight: '600' },
});
