import { useState } from 'react';

import { Text } from 'react-native';

import { NativeStackScreenProps } from '@react-navigation/native-stack';

import api from '../../core/api';

import { captchaPayload, isCaptchaReady, type CaptchaState } from '../../core/captcha';

import { extractApiError } from '../../core/getApiBaseUrl';

import { CaptchaField } from '../../components/auth/CaptchaField';

import { GuestStackParamList } from '../../navigation/types';

import { ScreenLayout } from '../../components/ui/ScreenLayout';

import { FormField } from '../../components/ui/FormField';

import { AppButton } from '../../components/ui/AppButton';

import { colors } from '../../constants/theme';



export function RegisterScreen({ navigation }: NativeStackScreenProps<GuestStackParamList, 'Register'>) {

  const [form, setForm] = useState({ clinic_name: '', owner_name: '', email: '', phone: '' });

  const [captcha, setCaptcha] = useState<CaptchaState>({});

  const [msg, setMsg] = useState('');

  const [devCode, setDevCode] = useState('');

  const set = (k: string, v: unknown) => setForm((f) => ({ ...f, [k]: v }));



  const submit = async () => {

    if (!isCaptchaReady(captcha)) {

      setMsg('Please complete the security check.');

      return;

    }

    setDevCode('');

    try {

      const { data } = await api.post('/auth/register', { ...form, ...captchaPayload(captcha, 'register') });

      const code = data.development_code ? String(data.development_code) : '';

      setMsg(data.message || 'Registration submitted. Check your email to verify.');

      setDevCode(code);

      if (form.email) {

        navigation.navigate('Verify', { email: form.email, code: code || undefined });

      }

    } catch (e: unknown) {

      setMsg(extractApiError(e));

    }

  };



  return (

    <ScreenLayout title="Register" subtitle="Create a clinic account">

      <FormField field={{ key: 'clinic_name', label: 'Clinic name', required: true }} value={form.clinic_name} onChange={(v) => set('clinic_name', v)} />

      <FormField field={{ key: 'owner_name', label: 'Owner name', required: true }} value={form.owner_name} onChange={(v) => set('owner_name', v)} />

      <FormField field={{ key: 'email', label: 'Email', type: 'email', required: true }} value={form.email} onChange={(v) => set('email', v)} />

      <FormField field={{ key: 'phone', label: 'Phone', type: 'tel' }} value={form.phone} onChange={(v) => set('phone', v)} />

      <CaptchaField context="register" value={captcha} onChange={setCaptcha} />

      {msg ? <Text style={{ color: msg.includes('submitted') || msg.includes('successful') ? colors.success : colors.danger, marginBottom: 12 }}>{msg}</Text> : null}

      {devCode ? <Text style={{ color: colors.textMuted, marginBottom: 12 }}>Dev verification code: {devCode}</Text> : null}

      <AppButton label="Register" icon="register" onPress={submit} />

      <AppButton label="Back to login" icon="back" variant="ghost" onPress={() => navigation.navigate('Login')} />

    </ScreenLayout>

  );

}



export function ForgotPasswordScreen({ navigation }: NativeStackScreenProps<GuestStackParamList, 'ForgotPassword'>) {

  const [email, setEmail] = useState('');

  const [captcha, setCaptcha] = useState<CaptchaState>({});

  const [msg, setMsg] = useState('');

  const submit = async () => {

    if (!isCaptchaReady(captcha)) {

      setMsg('Please complete the security check.');

      return;

    }

    try {

      await api.post('/auth/forgot-password', { email, ...captchaPayload(captcha, 'forgot_password') });

      setMsg('If the email exists, a reset link was sent.');

    } catch (e: unknown) {

      setMsg(extractApiError(e));

    }

  };

  return (

    <ScreenLayout title="Forgot password">

      <FormField field={{ key: 'email', label: 'Email', type: 'email', required: true }} value={email} onChange={(v) => setEmail(String(v))} />

      <CaptchaField context="forgot_password" value={captcha} onChange={setCaptcha} />

      {msg ? <Text style={{ color: colors.primary, marginBottom: 12 }}>{msg}</Text> : null}

      <AppButton label="Send reset link" icon="mail" onPress={submit} />

      <AppButton label="Back" icon="back" variant="ghost" onPress={() => navigation.goBack()} />

    </ScreenLayout>

  );

}



export function ResetPasswordScreen({ route, navigation }: NativeStackScreenProps<GuestStackParamList, 'ResetPassword'>) {

  const [password, setPassword] = useState('');

  const [password_confirmation, setConfirm] = useState('');

  const [msg, setMsg] = useState('');

  const submit = async () => {

    try {

      await api.post('/auth/reset-password', {

        email: route.params?.email,

        token: route.params?.token,

        password,

        password_confirmation,

      });

      navigation.navigate('Login');

    } catch (e: unknown) {

      setMsg(extractApiError(e));

    }

  };

  return (

    <ScreenLayout title="Reset password">

      <FormField field={{ key: 'password', label: 'New password', type: 'password', required: true }} value={password} onChange={(v) => setPassword(String(v))} />

      <FormField field={{ key: 'c', label: 'Confirm', type: 'password', required: true }} value={password_confirmation} onChange={(v) => setConfirm(String(v))} />

      {msg ? <Text style={{ color: colors.danger, marginBottom: 12 }}>{msg}</Text> : null}

      <AppButton label="Reset" icon="check" onPress={submit} />

    </ScreenLayout>

  );

}



export function VerifyScreen({ route, navigation }: NativeStackScreenProps<GuestStackParamList, 'Verify'>) {

  const [form, setForm] = useState({

    email: route.params?.email || '',

    code: route.params?.code || '',

    password: '',

    password_confirmation: '',

  });

  const [captcha, setCaptcha] = useState<CaptchaState>({});

  const [msg, setMsg] = useState('');

  const set = (k: string, v: unknown) => setForm((f) => ({ ...f, [k]: v }));



  const submit = async () => {

    if (!isCaptchaReady(captcha)) {

      setMsg('Please complete the security check.');

      return;

    }

    try {

      const { data } = await api.post('/auth/verify', { ...form, ...captchaPayload(captcha, 'verify') });

      setMsg(data.message || 'Verified. You can log in.');

      setTimeout(() => navigation.navigate('Login'), 800);

    } catch (e: unknown) {

      setMsg(extractApiError(e));

    }

  };

  return (

    <ScreenLayout title="Verify email" subtitle="Enter your code and set a password">

      <FormField field={{ key: 'email', label: 'Email', type: 'email', required: true }} value={form.email} onChange={(v) => set('email', v)} />

      <FormField field={{ key: 'code', label: 'Verification code', required: true }} value={form.code} onChange={(v) => set('code', v)} />

      <FormField field={{ key: 'password', label: 'Password', type: 'password', required: true }} value={form.password} onChange={(v) => set('password', v)} />

      <FormField field={{ key: 'password_confirmation', label: 'Confirm password', type: 'password', required: true }} value={form.password_confirmation} onChange={(v) => set('password_confirmation', v)} />

      <CaptchaField context="verify" value={captcha} onChange={setCaptcha} />

      {msg ? <Text style={{ color: colors.primary, marginBottom: 12 }}>{msg}</Text> : null}

      <AppButton label="Verify" icon="check" onPress={submit} />

    </ScreenLayout>

  );

}



export function CustomerOnboardScreen({ navigation }: NativeStackScreenProps<GuestStackParamList, 'CustomerOnboard'>) {

  const [customer_code, setCode] = useState('');

  const [captcha, setCaptcha] = useState<CaptchaState>({});

  const [msg, setMsg] = useState('');

  const submit = async () => {

    if (!isCaptchaReady(captcha)) {

      setMsg('Please complete the security check.');

      return;

    }

    try {

      const { data } = await api.post('/auth/customer-onboard', {

        customer_code,

        ...captchaPayload(captcha, 'customer_onboard'),

      });

      navigation.navigate('Verify', {

        email: data.email,

        code: data.code ? String(data.code) : undefined,

      });

    } catch (e: unknown) {

      setMsg(extractApiError(e));

    }

  };

  return (

    <ScreenLayout title="Customer access" subtitle="Enter the customer code from your clinic">

      <FormField field={{ key: 'code', label: 'Customer code', required: true }} value={customer_code} onChange={(v) => setCode(String(v))} />

      <CaptchaField context="customer_onboard" value={captcha} onChange={setCaptcha} />

      {msg ? <Text style={{ color: colors.danger, marginBottom: 12 }}>{msg}</Text> : null}

      <AppButton label="Continue to verification" icon="check" onPress={submit} />

      <AppButton label="Back to login" icon="back" variant="ghost" onPress={() => navigation.navigate('Login')} />

    </ScreenLayout>

  );

}

