import React, { useState } from 'react';
import {
  IonButton,
  IonContent,
  IonIcon,
  IonPage,
  IonSkeletonText,
  useIonViewWillEnter,
} from '@ionic/react';
import {
  cardOutline,
  createOutline,
  logOutOutline,
  mailOutline,
  notificationsOutline,
  personOutline,
  phonePortraitOutline,
  shieldCheckmarkOutline,
} from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import SettingsRow from '../components/SettingsRow';
import sarahAvatarImage from '../assets/sarah.jpg';
import '../styles/profile.css';

type Profile = {
  id: string;
  first_name: string;
  last_name: string;
  full_name: string;
  phone: string;
  country_of_residence: string;
  avatar_path: string | null;
  notification_push_enabled: boolean;
  notification_email_enabled: boolean;
  notification_sms_enabled: boolean;
};

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: sarahAvatarImage,
    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 = (
  profile: Profile,
  avatarUrl: string | null
) => {
  const payload: PreviewProfilePayload = {
    first_name: profile.first_name,
    last_name: profile.last_name,
    phone: profile.phone,
    country_of_residence: profile.country_of_residence,
    avatar_url: avatarUrl,
    notification_push_enabled: profile.notification_push_enabled,
    notification_email_enabled: profile.notification_email_enabled,
    notification_sms_enabled: profile.notification_sms_enabled,
  };
  localStorage.setItem(PREVIEW_PROFILE_STORAGE_KEY, JSON.stringify(payload));
};

const buildPreviewProfile = () => {
  const payload = getPreviewProfilePayload();
  const profile: Profile = {
    id: 'preview-profile',
    first_name: payload.first_name,
    last_name: payload.last_name,
    full_name: `${payload.first_name} ${payload.last_name}`,
    phone: payload.phone,
    country_of_residence: payload.country_of_residence,
    avatar_path: null,
    notification_push_enabled: payload.notification_push_enabled,
    notification_email_enabled: payload.notification_email_enabled,
    notification_sms_enabled: payload.notification_sms_enabled,
  };

  return { profile, avatarUrl: payload.avatar_url };
};

const ProfilePage: React.FC = () => {
  const history = useHistory();
  const { user, signOut, refreshProfile } = useAuth();
  const [profile, setProfile] = useState<Profile | null>(null);
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [signingOut, setSigningOut] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useIonViewWillEnter(() => {
    void loadProfile();
  });

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

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

    if (!user) {
      const preview = buildPreviewProfile();
      setProfile(preview.profile);
      setAvatarUrl(preview.avatarUrl);
      setLoading(false);
      return;
    }

    const { data, error: profileError } = await supabase
      .from('profiles')
      .select('*')
      .eq('id', user.id)
      .single();

    if (profileError || !data) {
      showError(profileError?.message ?? 'Profile not found');
      const preview = buildPreviewProfile();
      setProfile(preview.profile);
      setAvatarUrl(preview.avatarUrl);
      setLoading(false);
      return;
    }

    const nextProfile = data as Profile;
    setProfile(nextProfile);
    if (nextProfile.avatar_path) {
      const { data: signed } = await supabase.storage
        .from('avatars')
        .createSignedUrl(nextProfile.avatar_path, 3600);
      setAvatarUrl(signed?.signedUrl ?? null);
    } else {
      setAvatarUrl(null);
    }
    setLoading(false);
  };

  const handleTogglePreference = async (
    field:
      | 'notification_push_enabled'
      | 'notification_email_enabled'
      | 'notification_sms_enabled',
    checked: boolean
  ) => {
    if (!profile) return;
    const previous = profile;
    const next = { ...profile, [field]: checked };
    setProfile(next);

    if (!user) {
      savePreviewProfilePayload(next, avatarUrl);
      return;
    }

    const updatedAt = new Date().toISOString();
    const updates =
      field === 'notification_push_enabled'
        ? { notification_push_enabled: checked, updated_at: updatedAt }
        : field === 'notification_email_enabled'
          ? { notification_email_enabled: checked, updated_at: updatedAt }
          : { notification_sms_enabled: checked, updated_at: updatedAt };

    const { error: updateError } = await supabase
      .from('profiles')
      .update(updates)
      .eq('id', profile.id);

    if (updateError) {
      setProfile(previous);
      showError(updateError.message);
      return;
    }
    await refreshProfile();
  };

  const handleSignOut = async () => {
    setSigningOut(true);
    try {
      await FirebaseAuthentication.signOut().catch(() => undefined);
      await signOut();
      history.replace('/auth');
    } finally {
      setSigningOut(false);
    }
  };

  const initials =
    profile?.full_name
      ?.split(' ')
      .map((part) => part.charAt(0))
      .slice(0, 2)
      .join('')
      .toUpperCase() || '?';

  const paymentMethodsCount = 0;

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonContent
        fullscreen
        className="profile-shell"
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-start': '0px',
            '--padding-end': '0px',
          } as React.CSSProperties
        }
      >
        <h1
          className="profile-page-title"
          style={{ paddingTop: 'calc(16px + var(--ion-safe-area-top))' }}
        >
          Profile
        </h1>
        {error && (
          <p style={{ margin: '0 20px 12px', color: '#dc2626', fontSize: 13 }}>
            {error}
          </p>
        )}

        {loading ? (
          <div className="profile-summary-card">
            <IonSkeletonText
              animated
              style={{ width: 72, height: 72, borderRadius: 24, flexShrink: 0 }}
            />
            <div style={{ flex: 1 }}>
              <IonSkeletonText animated style={{ width: '70%', height: 22 }} />
              <IonSkeletonText animated style={{ width: '90%', height: 14 }} />
            </div>
          </div>
        ) : profile ? (
          <>
            <div className="profile-summary-card">
              <div className="psc-avatar-shell">
                {avatarUrl ? (
                  <img
                    src={avatarUrl}
                    alt={profile.full_name}
                    className="psc-avatar"
                  />
                ) : (
                  <div className="psc-avatar-placeholder">{initials}</div>
                )}
              </div>
              <div className="psc-info">
                <h2 className="psc-name">{profile.full_name}</h2>
                <p className="psc-location">{profile.country_of_residence}</p>
              </div>
              <IonButton
                className="psc-edit-btn"
                onClick={() => history.push('/profile/edit')}
              >
                <IonIcon icon={createOutline} slot="icon-only" />
              </IonButton>
            </div>

            <div className="profile-quick-actions-card">
              <button
                type="button"
                className="profile-quick-action"
                onClick={() => history.push('/profile/edit')}
              >
                <span className="profile-quick-action-icon profile-quick-action-icon--accent">
                  <IonIcon icon={createOutline} />
                </span>
                <span className="profile-quick-action-copy">
                  <span className="profile-quick-action-title">
                    Edit your info
                  </span>
                  <span className="profile-quick-action-subtitle">
                    Update your name, number and country
                  </span>
                </span>
              </button>

              <button
                type="button"
                className="profile-quick-action"
                onClick={() => history.push('/profile/edit')}
              >
                <span className="profile-quick-action-icon profile-quick-action-icon--soft">
                  <IonIcon icon={personOutline} />
                </span>
                <span className="profile-quick-action-copy">
                  <span className="profile-quick-action-title">
                    Change profile photo
                  </span>
                  <span className="profile-quick-action-subtitle">
                    Pick a new photo from your gallery
                  </span>
                </span>
              </button>
            </div>

            <h2 className="settings-section-title">Payments</h2>
            <div className="settings-card">
              <SettingsRow
                icon={cardOutline}
                title="Saved cards"
                subtitle={
                  paymentMethodsCount > 0
                    ? `${paymentMethodsCount} saved for faster checkout`
                    : 'No saved cards yet'
                }
                onClick={() =>
                  showError(
                    'Saved cards will be added when payments are connected in a later phase'
                  )
                }
              />
            </div>

            <h2 className="settings-section-title">Account</h2>
            <div className="settings-card">
              <SettingsRow
                icon={personOutline}
                title="Edit profile"
                subtitle="Name, phone, country, avatar"
                onClick={() => history.push('/profile/edit')}
              />
              <SettingsRow
                icon={notificationsOutline}
                title="Notifications"
                subtitle="Open your notification inbox"
                onClick={() => history.push('/notifications')}
              />
              <SettingsRow
                icon={shieldCheckmarkOutline}
                title="Security settings"
                subtitle="Password and account safety"
                type="button"
                onClick={() =>
                  showError(
                    'Security settings will be available after MVP launch'
                  )
                }
              />
            </div>

            <h2 className="settings-section-title">Preferences</h2>
            <div className="settings-card">
              <SettingsRow
                icon={notificationsOutline}
                title="Push notifications"
                type="toggle"
                checked={profile.notification_push_enabled}
                onToggle={(checked) =>
                  handleTogglePreference('notification_push_enabled', checked)
                }
              />
              <SettingsRow
                icon={mailOutline}
                title="Email updates"
                type="toggle"
                checked={profile.notification_email_enabled}
                onToggle={(checked) =>
                  handleTogglePreference('notification_email_enabled', checked)
                }
              />
              <SettingsRow
                icon={phonePortraitOutline}
                title="SMS updates"
                type="toggle"
                checked={profile.notification_sms_enabled}
                onToggle={(checked) =>
                  handleTogglePreference('notification_sms_enabled', checked)
                }
              />
            </div>

            <div className="settings-card">
              <SettingsRow
                icon={logOutOutline}
                title={signingOut ? 'Signing out...' : 'Sign out'}
                type="button"
                destructive
                onClick={handleSignOut}
              />
            </div>
          </>
        ) : null}
      </IonContent>
    </IonPage>
  );
};

export default ProfilePage;
