import React, { useMemo, useState } from 'react';
import {
  IonButton,
  IonContent,
  IonIcon,
  IonPage,
  IonRefresher,
  IonRefresherContent,
  IonSkeletonText,
  useIonViewWillEnter,
} from '@ionic/react';
import { addOutline, peopleOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import dadImage from '../assets/dad.jpg';
import momImage from '../assets/mom.jpg';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import ListSearchRow from '../components/ListSearchRow';
import RecipientListCard, {
  RecipientListItem,
} from '../components/RecipientListCard';
import '../styles/recipients.css';

type RecipientRow = {
  id: string;
  first_name: string;
  last_name: string;
  relationship: string;
  country: string;
  city: string;
  photo_path: string | null;
  created_at: string;
};

type ActivityRow = {
  recipient_id: string | null;
  event_at: string;
};

const formatLastActivity = (dateText?: string) => {
  if (!dateText) return 'No support yet';
  const diffMs = Date.now() - new Date(dateText).getTime();
  const diffDays = Math.max(0, Math.floor(diffMs / 86400000));
  if (diffDays === 0) return 'Today';
  if (diffDays === 1) return 'Yesterday';
  return `${diffDays} days ago`;
};

const getSeededRecipientImage = (firstName?: string | null) => {
  const normalized = firstName?.trim().toLowerCase();
  if (normalized === 'mum' || normalized === 'mom') return momImage;
  if (normalized === 'dad' || normalized === 'father') return dadImage;
  return null;
};

const RecipientsPage: React.FC = () => {
  const history = useHistory();
  const { user } = useAuth();
  const [recipients, setRecipients] = useState<RecipientListItem[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  const loadRecipients = async () => {
    if (!user) {
      // Auth bypass mode: fetch seeded preview recipients from Supabase
      setLoading(true);
      setError(null);
      const [recipientsResult, activityResult] = await Promise.all([
        supabase
          .from('recipients')
          .select(
            'id,first_name,last_name,relationship,country,city,photo_path,created_at'
          )
          .eq('user_id', '00000000-0000-0000-0000-000000000000')
          .order('created_at', { ascending: false }),
        supabase
          .from('activity_events')
          .select('recipient_id,event_at')
          .eq('user_id', '00000000-0000-0000-0000-000000000000')
          .order('event_at', { ascending: false })
          .limit(100),
      ]);

      const queryError = recipientsResult.error ?? activityResult.error;
      if (queryError) {
        showError(queryError.message);
        setLoading(false);
        return;
      }

      const activities = (activityResult.data ?? []) as ActivityRow[];
      const list = await Promise.all(
        ((recipientsResult.data ?? []) as RecipientRow[]).map(
          async (recipient) => {
            const latestActivity = activities.find(
              (a) => a.recipient_id === recipient.id
            );

            let avatarUrl = null;
            if (recipient.photo_path) {
              const { data: urlData } = await supabase.storage
                .from('recipient-photos')
                .createSignedUrl(recipient.photo_path, 3600);
              avatarUrl = urlData?.signedUrl ?? null;
            }

            if (!avatarUrl) {
              avatarUrl = getSeededRecipientImage(recipient.first_name);
            }

            return {
              id: recipient.id,
              firstName: recipient.first_name,
              lastName: recipient.last_name,
              relationship: recipient.relationship,
              location: `${recipient.city}, ${recipient.country}`,
              lastActivityText: formatLastActivity(latestActivity?.event_at),
              avatarUrl,
            };
          }
        )
      );
      setRecipients(list);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    const [recipientsResult, activityResult] = await Promise.all([
      supabase
        .from('recipients')
        .select(
          'id,first_name,last_name,relationship,country,city,photo_path,created_at'
        )
        .eq('user_id', user.id)
        .eq('is_active', true)
        .order('created_at', { ascending: false }),
      supabase
        .from('activity_events')
        .select('recipient_id,event_at')
        .eq('user_id', user.id)
        .order('event_at', { ascending: false })
        .limit(100),
    ]);

    const queryError = recipientsResult.error ?? activityResult.error;
    if (queryError) {
      showError(queryError.message);
      setLoading(false);
      return;
    }

    const activities = (activityResult.data ?? []) as ActivityRow[];
    const list = await Promise.all(
      ((recipientsResult.data ?? []) as RecipientRow[]).map(
        async (recipient) => {
          const latestActivity = activities.find(
            (activity) => activity.recipient_id === recipient.id
          );
          let avatarUrl = recipient.photo_path
            ? ((
                await supabase.storage
                  .from('recipient-photos')
                  .createSignedUrl(recipient.photo_path, 3600)
              ).data?.signedUrl ?? null)
            : null;

          if (!avatarUrl) {
            avatarUrl = getSeededRecipientImage(recipient.first_name);
          }

          return {
            id: recipient.id,
            firstName: recipient.first_name,
            lastName: recipient.last_name,
            relationship: recipient.relationship,
            location: `${recipient.city}, ${recipient.country}`,
            lastActivityText: formatLastActivity(latestActivity?.event_at),
            avatarUrl,
          };
        }
      )
    );

    setRecipients(list);
    setLoading(false);
  };

  const visibleRecipients = useMemo(() => {
    const query = searchTerm.trim().toLowerCase();
    if (!query) return recipients;
    return recipients.filter((recipient) =>
      [
        recipient.firstName,
        recipient.lastName,
        recipient.relationship,
        recipient.location,
      ]
        .join(' ')
        .toLowerCase()
        .includes(query)
    );
  }, [recipients, searchTerm]);

  const handleRefresh = async (event: CustomEvent) => {
    await loadRecipients();
    event.detail.complete();
  };

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonContent
        fullscreen
        className="recipients-shell"
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-start': '0px',
            '--padding-end': '0px',
            '--padding-top': '0px',
          } as React.CSSProperties
        }
      >
        <IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
          <IonRefresherContent />
        </IonRefresher>

        <div
          className="recipients-top-row"
          style={{ padding: 'calc(16px + var(--ion-safe-area-top)) 0 12px' }}
        >
          <div>
            <h1 className="recipients-page-title">Loved ones</h1>
            <p className="rlc-location" style={{ marginTop: '4px' }}>
              Manage family and care recipients
            </p>
          </div>
          <IonButton
            className="recipients-add-btn"
            onClick={() => history.push('/recipients/new')}
          >
            <IonIcon icon={addOutline} slot="start" />
            Add
          </IonButton>
        </div>

        <ListSearchRow
          value={searchTerm}
          onChange={setSearchTerm}
          placeholder="Search loved ones..."
        />

        {error && (
          <p
            style={{
              margin: '0 20px 12px',
              color: '#dc2626',
              fontSize: '13px',
            }}
          >
            {error}
          </p>
        )}

        {loading ? (
          <div>
            {[1, 2, 3].map((item) => (
              <div key={item} className="recipient-list-card">
                <IonSkeletonText
                  animated
                  style={{
                    width: '52px',
                    height: '52px',
                    borderRadius: '16px',
                    flexShrink: 0,
                  }}
                />
                <div style={{ flex: 1 }}>
                  <IonSkeletonText
                    animated
                    style={{ width: '60%', height: '16px' }}
                  />
                  <IonSkeletonText
                    animated
                    style={{ width: '40%', height: '12px' }}
                  />
                </div>
              </div>
            ))}
          </div>
        ) : visibleRecipients.length === 0 ? (
          <div className="empty-state-card">
            <IonIcon icon={peopleOutline} className="esc-icon" />
            <h2 className="esc-title">
              {recipients.length === 0
                ? 'No loved ones yet'
                : 'No matches found'}
            </h2>
            <p className="esc-msg">
              {recipients.length === 0
                ? 'Add your first loved one so you can send support with confidence.'
                : 'Try a different name, relationship, or city.'}
            </p>
            {recipients.length === 0 && (
              <IonButton
                onClick={() => history.push('/recipients/new')}
                style={
                  {
                    '--background': '#6d28d9',
                    '--border-radius': '999px',
                    '--box-shadow': 'none',
                  } as React.CSSProperties
                }
              >
                <IonIcon icon={addOutline} slot="start" />
                Add loved one
              </IonButton>
            )}
          </div>
        ) : (
          <div>
            {visibleRecipients.map((recipient) => (
              <RecipientListCard
                key={recipient.id}
                recipient={recipient}
                onClick={(id) => history.push(`/recipients/${id}`)}
              />
            ))}
          </div>
        )}
      </IonContent>
    </IonPage>
  );
};

export default RecipientsPage;
