import React, { useEffect, useRef, useState } from 'react';
import { IonButton, IonContent, IonInput, IonPage } from '@ionic/react';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import AvatarPicker from '../components/AvatarPicker';
import '../styles/auth.css';

type ProfileDraft = {
  first_name?: string | null;
  last_name?: string | null;
  phone?: string | null;
  country_of_residence?: string | null;
  avatar_path?: string | null;
};

const SetupProfilePage: React.FC = () => {
  const history = useHistory();
  const { user, setProfile, signOut } = useAuth();

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [country, setCountry] = useState('');
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const messageTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const mountedRef = useRef(true);
  const [loading, setLoading] = useState(false);
  const [prefilling, setPrefilling] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
      if (messageTimerRef.current) {
        clearTimeout(messageTimerRef.current);
      }
    };
  }, []);

  useEffect(() => {
    loadExistingProfile();
  }, [user?.id]);

  const showError = (message: string) => {
    if (messageTimerRef.current) {
      clearTimeout(messageTimerRef.current);
    }
    setError(message);
    messageTimerRef.current = setTimeout(() => {
      if (mountedRef.current) {
        setError(null);
      }
    }, 4000);
  };

  const loadExistingProfile = async () => {
    if (!user) {
      setPrefilling(false);
      return;
    }

    setPrefilling(true);
    let profile: ProfileDraft | null = null;
    let profileLoadError: unknown = null;

    try {
      const profileLoadRequest = supabase
        .from('profiles')
        .select('first_name,last_name,phone,country_of_residence,avatar_path')
        .eq('id', user.id)
        .maybeSingle();

      const result = await Promise.race([
        profileLoadRequest,
        new Promise<never>((_, reject) =>
          setTimeout(
            () => reject(new Error('Profile setup loading timed out.')),
            8000
          )
        ),
      ]);

      profile = result.data as ProfileDraft | null;
      profileLoadError = result.error;
    } catch (loadError) {
      profileLoadError = loadError;
    }

    if (!mountedRef.current) return;

    if (profileLoadError) {
      console.error(
        '[SetupProfilePage] Failed to load existing profile',
        profileLoadError
      );
      showError(
        'We could not load your profile yet. You can still finish setup.'
      );
    }
    if (profile) {
      setFirstName(profile.first_name ?? '');
      setLastName(profile.last_name ?? '');
      setPhone(profile.phone ?? '');
      setCountry(profile.country_of_residence ?? '');
      if (profile.avatar_path) {
        const { data: publicUrlData } = supabase.storage
          .from('avatars')
          .getPublicUrl(profile.avatar_path);
        setAvatarPreview(publicUrlData.publicUrl);
      }
    } else if (user.user_metadata?.full_name) {
      const parts = String(user.user_metadata.full_name).split(' ');
      setFirstName(parts[0] ?? '');
      setLastName(parts.slice(1).join(' '));
    }
    setPrefilling(false);
  };

  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = () => {
      if (!mountedRef.current) return;
      setAvatarFile(file);
      setAvatarPreview(
        typeof reader.result === 'string' ? reader.result : null
      );
    };
    reader.onerror = () => {
      showError(
        'We could not preview that image. Please choose another photo.'
      );
    };
    reader.readAsDataURL(file);
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();

    if (!user) {
      showError('Please sign in again to complete your profile');
      return;
    }

    const cleanFirstName = firstName.trim();
    const cleanLastName = lastName.trim();
    const cleanPhone = phone.trim();
    const cleanCountry = country.trim();

    if (!cleanFirstName || !cleanLastName || !cleanPhone || !cleanCountry) {
      showError('Please complete all profile fields');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      let avatarPath: string | null = null;
      if (avatarFile) {
        const extension = avatarFile.name.split('.').pop() || 'jpg';
        avatarPath = `${user.id}/${Date.now()}.${extension}`;
        const uploadRequest = supabase.storage
          .from('avatars')
          .upload(avatarPath, avatarFile);
        const { error: uploadError } = await Promise.race([
          uploadRequest,
          new Promise<never>((_, reject) =>
            setTimeout(
              () =>
                reject(new Error('Photo upload timed out. Please try again.')),
              12000
            )
          ),
        ]);

        if (uploadError) {
          showError(uploadError.message);
          setLoading(false);
          return;
        }
      }

      const now = new Date().toISOString();
      const profilePayload = {
        id: user.id,
        first_name: cleanFirstName,
        last_name: cleanLastName,
        full_name: `${cleanFirstName} ${cleanLastName}`,
        phone: cleanPhone,
        country_of_residence: cleanCountry,
        ...(avatarPath ? { avatar_path: avatarPath } : {}),
        notification_push_enabled: true,
        notification_email_enabled: true,
        notification_sms_enabled: false,
        updated_at: now,
      };

      const profileSaveRequest = supabase
        .from('profiles')
        .upsert(profilePayload, { onConflict: 'id' })
        .select('*')
        .single();

      const { data: savedProfile, error: profileError } = await Promise.race([
        profileSaveRequest,
        new Promise<never>((_, reject) =>
          setTimeout(
            () =>
              reject(new Error('Profile save timed out. Please try again.')),
            12000
          )
        ),
      ]);

      if (profileError) {
        showError(profileError.message);
        setLoading(false);
        return;
      }

      if (!mountedRef.current) return;

      setLoading(false);
      setProfile(savedProfile);
      history.replace('/home');
    } catch (submitError: any) {
      if (!mountedRef.current) return;
      showError(
        submitError.message || 'Profile setup failed. Please try again.'
      );
      setLoading(false);
    }
  };

  const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();

  const handleLogout = async () => {
    if (loading || prefilling) return;

    setLoading(true);
    setError(null);

    try {
      await signOut();
      history.replace('/auth');
    } catch (logoutError: any) {
      showError(
        logoutError?.message || 'We could not sign you out. Please try again.'
      );
      setLoading(false);
    }
  };

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonContent
        className="auth-content"
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-start': '0px',
            '--padding-end': '0px',
            '--padding-top': '0px',
            '--padding-bottom': '0px',
          } as React.CSSProperties
        }
      >
        <div className="auth-shell">
          <div className="auth-brand-block">
            <h4 className="auth-eyebrow">Profile setup</h4>
            <h1 className="auth-heading">Tell us about you</h1>
            <p className="auth-subtitle">
              We use this to personalise your Kumusha dashboard and keep your
              account secure.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="auth-form-card">
            <AvatarPicker
              previewUrl={avatarPreview}
              onFileChange={handleAvatarChange}
              initials={initials || undefined}
              disabled={loading || prefilling}
            />

            <IonInput
              type="text"
              label="First name"
              labelPlacement="floating"
              value={firstName}
              onIonInput={(event) => setFirstName(event.detail.value ?? '')}
              disabled={loading || prefilling}
              placeholder="e.g. Tadiwa"
              className="auth-field"
            />
            <IonInput
              type="text"
              label="Last name"
              labelPlacement="floating"
              value={lastName}
              onIonInput={(event) => setLastName(event.detail.value ?? '')}
              disabled={loading || prefilling}
              placeholder="e.g. Moyo"
              className="auth-field"
            />
            <IonInput
              type="tel"
              inputMode="tel"
              label="Mobile number"
              labelPlacement="floating"
              value={phone}
              onIonInput={(event) => setPhone(event.detail.value ?? '')}
              disabled={loading || prefilling}
              placeholder="e.g. +44 7123 456789"
              className="auth-field"
            />
            <IonInput
              type="text"
              label="Country of residence"
              labelPlacement="floating"
              value={country}
              onIonInput={(event) => setCountry(event.detail.value ?? '')}
              disabled={loading || prefilling}
              placeholder="e.g. United Kingdom"
              className="auth-field"
            />

            {error && (
              <p className="auth-status-text" style={{ color: '#dc2626' }}>
                {error}
              </p>
            )}

            <div className="setup-profile-actions-row">
              <IonButton
                type="button"
                fill="outline"
                disabled={loading || prefilling}
                onClick={handleLogout}
                className="setup-profile-secondary-btn"
              >
                Logout
              </IonButton>
              <IonButton
                type="submit"
                expand="block"
                disabled={loading || prefilling}
                className="setup-profile-primary-btn"
              >
                {loading ? 'Saving profile...' : 'Finish setup'}
              </IonButton>
            </div>
          </form>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default SetupProfilePage;
