import React, { useEffect, useState } from 'react';
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonIcon,
  IonInput,
  IonPage,
  IonTitle,
  IonToolbar,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import AvatarPicker from '../components/AvatarPicker';
import '../styles/profile.css';

type Profile = {
  id: string;
  first_name: string;
  last_name: string;
  phone: string;
  country_of_residence: string;
  avatar_path: string | null;
};

type PreviewProfilePayload = {
  first_name: string;
  last_name: string;
  phone: string;
  country_of_residence: string;
  avatar_url: string | null;
  notification_push_enabled: boolean;
  notification_email_enabled: boolean;
  notification_sms_enabled: boolean;
};

const PREVIEW_PROFILE_STORAGE_KEY = 'kumusha-preview-profile';

const getPreviewProfilePayload = (): PreviewProfilePayload => {
  const fallback: PreviewProfilePayload = {
    first_name: 'Sarah',
    last_name: 'Moyo',
    phone: '+44 7123 456789',
    country_of_residence: 'United Kingdom',
    avatar_url: null,
    notification_push_enabled: true,
    notification_email_enabled: true,
    notification_sms_enabled: false,
  };

  try {
    const saved = localStorage.getItem(PREVIEW_PROFILE_STORAGE_KEY);
    return saved ? { ...fallback, ...JSON.parse(saved) } : fallback;
  } catch {
    return fallback;
  }
};

const savePreviewProfilePayload = (payload: PreviewProfilePayload) => {
  localStorage.setItem(PREVIEW_PROFILE_STORAGE_KEY, JSON.stringify(payload));
};

const EditProfilePage: React.FC = () => {
  const history = useHistory();
  const { user, refreshProfile } = useAuth();
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [country, setCountry] = useState('');
  const [avatarPath, setAvatarPath] = useState<string | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const showError = (message: string) => {
    setError(message);
    setTimeout(() => setError(null), 4000);
  };

  const loadProfile = async () => {
    setLoading(true);

    if (!user) {
      const preview = getPreviewProfilePayload();
      setFirstName(preview.first_name);
      setLastName(preview.last_name);
      setPhone(preview.phone);
      setCountry(preview.country_of_residence);
      setAvatarPath(null);
      setAvatarPreview(preview.avatar_url);
      setLoading(false);
      return;
    }

    const { data, error: loadError } = await supabase
      .from('profiles')
      .select('id,first_name,last_name,phone,country_of_residence,avatar_path')
      .eq('id', user.id)
      .single();

    if (loadError || !data) {
      showError(loadError?.message ?? 'Profile not found');
      const preview = getPreviewProfilePayload();
      setFirstName(preview.first_name);
      setLastName(preview.last_name);
      setPhone(preview.phone);
      setCountry(preview.country_of_residence);
      setAvatarPath(null);
      setAvatarPreview(preview.avatar_url);
      setLoading(false);
      return;
    }

    const profile = data as Profile;
    setFirstName(profile.first_name ?? '');
    setLastName(profile.last_name ?? '');
    setPhone(profile.phone ?? '');
    setCountry(profile.country_of_residence ?? '');
    setAvatarPath(profile.avatar_path);
    if (profile.avatar_path) {
      const { data: signed } = await supabase.storage
        .from('avatars')
        .createSignedUrl(profile.avatar_path, 3600);
      setAvatarPreview(signed?.signedUrl ?? null);
    }
    setLoading(false);
  };

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

    const reader = new FileReader();
    reader.onload = () => {
      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();
    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 fields');
      return;
    }

    if (!user) {
      setSaving(true);
      savePreviewProfilePayload({
        ...getPreviewProfilePayload(),
        first_name: cleanFirstName,
        last_name: cleanLastName,
        phone: cleanPhone,
        country_of_residence: cleanCountry,
        avatar_url: avatarPreview,
      });
      setSaving(false);
      history.replace('/profile');
      return;
    }

    setSaving(true);
    let nextAvatarPath = avatarPath;
    if (avatarFile) {
      const extension = avatarFile.name.split('.').pop() || 'jpg';
      nextAvatarPath = `${user.id}/${Date.now()}.${extension}`;
      const { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(nextAvatarPath, avatarFile);
      if (uploadError) {
        showError(uploadError.message);
        setSaving(false);
        return;
      }
    }

    const { error: updateError } = await supabase
      .from('profiles')
      .update({
        first_name: cleanFirstName,
        last_name: cleanLastName,
        full_name: `${cleanFirstName} ${cleanLastName}`,
        phone: cleanPhone,
        country_of_residence: cleanCountry,
        avatar_path: nextAvatarPath,
        updated_at: new Date().toISOString(),
      })
      .eq('id', user.id);

    if (updateError) {
      showError(updateError.message);
      setSaving(false);
      return;
    }

    await refreshProfile();
    setSaving(false);
    history.replace('/profile');
  };

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

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonHeader className="ion-no-border">
        <IonToolbar
          style={
            {
              '--background': '#fafafa',
              '--border-width': '0px',
            } as React.CSSProperties
          }
        >
          <IonButtons slot="start">
            <IonButton
              className="profile-back-button"
              fill="clear"
              onClick={() =>
                history.length > 1
                  ? history.goBack()
                  : history.replace('/profile')
              }
              aria-label="Go back"
            >
              <IonIcon icon={chevronBackOutline} slot="icon-only" />
            </IonButton>
          </IonButtons>
          <IonTitle style={{ fontSize: 18, fontWeight: 700 }}>
            Edit profile
          </IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent
        className="edit-profile-shell"
        style={{ '--background': '#fafafa' } as React.CSSProperties}
      >
        <form onSubmit={handleSubmit}>
          <div className="edit-profile-card">
            <AvatarPicker
              previewUrl={avatarPreview}
              onFileChange={handleAvatarChange}
              initials={initials || undefined}
              disabled={loading || saving}
            />
            <IonInput
              className="epc-field"
              type="text"
              label="First name"
              labelPlacement="floating"
              placeholder="e.g. Tadiwa"
              value={firstName}
              disabled={loading || saving}
              onIonInput={(event) => setFirstName(event.detail.value ?? '')}
            />
            <IonInput
              className="epc-field"
              type="text"
              label="Last name"
              labelPlacement="floating"
              placeholder="e.g. Moyo"
              value={lastName}
              disabled={loading || saving}
              onIonInput={(event) => setLastName(event.detail.value ?? '')}
            />
            <IonInput
              className="epc-field"
              type="tel"
              inputMode="tel"
              label="Mobile number"
              labelPlacement="floating"
              placeholder="e.g. +44 7123 456789"
              value={phone}
              disabled={loading || saving}
              onIonInput={(event) => setPhone(event.detail.value ?? '')}
            />
            <IonInput
              className="epc-field"
              type="text"
              label="Country of residence"
              labelPlacement="floating"
              placeholder="e.g. United Kingdom"
              value={country}
              disabled={loading || saving}
              onIonInput={(event) => setCountry(event.detail.value ?? '')}
            />
            {error && (
              <p style={{ margin: 0, color: '#dc2626', fontSize: 13 }}>
                {error}
              </p>
            )}
          </div>

          <IonButton
            type="submit"
            expand="block"
            className="epc-save-btn"
            disabled={loading || saving}
          >
            {saving ? 'Saving...' : 'Save profile'}
          </IonButton>
        </form>
      </IonContent>
    </IonPage>
  );
};

export default EditProfilePage;
