import React, { useState } from 'react';
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonIcon,
  IonPage,
  IonSkeletonText,
  IonTitle,
  IonToolbar,
  useIonViewWillEnter,
} from '@ionic/react';
import basketIcon from '../assets/basket.png';
import momImage from '../assets/mom.jpg';
import dadImage from '../assets/dad.jpg';
import {
  chevronBackOutline,
  createOutline,
  heartOutline,
  alertCircleOutline,
  timeOutline,
  flashOutline,
  medkitOutline,
  cartOutline,
  wifiOutline,
  checkmarkCircleOutline,
  shareSocialOutline,
  paperPlaneOutline,
} from 'ionicons/icons';
import { useHistory, useParams } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import '../styles/recipients.css';

type Params = { id: string };

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

type OrderRow = {
  id: string;
  service_type: string;
  status: string;
  amount: number;
  created_at: string;
  merchant_id?: string | null;
  merchants?: { name: string } | null;
};

type CareAlertRow = {
  id: string;
  title: string;
  body: string;
  severity: string;
  service_type: string | null;
  due_at: string | null;
};

const RecipientDetailPage: React.FC = () => {
  const history = useHistory();
  const { id } = useParams<Params>();
  const { user } = useAuth();
  const [recipient, setRecipient] = useState<Recipient | null>(null);
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const [groupedOrders, setGroupedOrders] = useState<
    { label: string; items: OrderRow[] }[]
  >([]);
  const [careAlerts, setCareAlerts] = useState<CareAlertRow[]>([]);
  const [totalAssistance, setTotalAssistance] = useState(0);
  const [orderCount, setOrderCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

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

    const normalizedName = firstName?.trim().toLowerCase();
    if (normalizedName === 'mum' || normalizedName === 'mom') return momImage;
    if (normalizedName === 'dad' || normalizedName === 'father')
      return dadImage;
    return null;
  };

  const resolveRecipientAvatar = async (nextRecipient: Recipient) => {
    const seededImage = getSeededRecipientImage(
      nextRecipient.first_name,
      nextRecipient.photo_path
    );
    if (seededImage) {
      setAvatarUrl(seededImage);
      return;
    }

    if (!nextRecipient.photo_path) {
      setAvatarUrl(null);
      return;
    }

    const { data } = await supabase.storage
      .from('recipient-photos')
      .createSignedUrl(nextRecipient.photo_path, 3600);
    setAvatarUrl(data?.signedUrl ?? null);
  };

  const groupOrdersByDate = (orders: OrderRow[]) => {
    const groups: { label: string; items: OrderRow[] }[] = [];
    let currentLabel = '';
    let currentItems: OrderRow[] = [];

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    for (const order of orders) {
      const orderDate = new Date(order.created_at);
      orderDate.setHours(0, 0, 0, 0);

      let label = '';
      if (orderDate.getTime() === today.getTime()) {
        label = 'Today';
      } else if (orderDate.getTime() === yesterday.getTime()) {
        label = 'Yesterday';
      } else {
        label = orderDate.toLocaleDateString(undefined, {
          month: 'short',
          day: 'numeric',
          year:
            orderDate.getFullYear() !== today.getFullYear()
              ? 'numeric'
              : undefined,
        });
      }

      if (label !== currentLabel) {
        if (currentItems.length > 0) {
          groups.push({ label: currentLabel, items: currentItems });
        }
        currentLabel = label;
        currentItems = [order];
      } else {
        currentItems.push(order);
      }
    }
    if (currentItems.length > 0) {
      groups.push({ label: currentLabel, items: currentItems });
    }
    return groups;
  };

  const loadRecipientDetail = async () => {
    if (!user) {
      const [recipientResult, ordersResult, careAlertsResult] =
        await Promise.all([
          supabase
            .from('recipients')
            .select(
              'id,first_name,last_name,relationship,country,city,mobile_number,photo_path'
            )
            .eq('id', id)
            .eq('user_id', '00000000-0000-0000-0000-000000000000')
            .single(),
          supabase
            .from('support_orders')
            .select(
              'id,service_type,status,amount,created_at,merchant_id,merchants(name)'
            )
            .eq('recipient_id', id)
            .eq('user_id', '00000000-0000-0000-0000-000000000000')
            .order('created_at', { ascending: false }),
          supabase
            .from('care_alerts')
            .select('id,title,body,severity,service_type,due_at')
            .eq('recipient_id', id)
            .eq('user_id', '00000000-0000-0000-0000-000000000000')
            .is('dismissed_at', null)
            .order('due_at', { ascending: true, nullsFirst: false })
            .limit(3),
        ]);

      const queryError =
        recipientResult.error ?? ordersResult.error ?? careAlertsResult.error;
      if (queryError || !recipientResult.data) {
        showError(queryError?.message ?? 'Loved one not found');
        setLoading(false);
        return;
      }

      const nextRecipient = recipientResult.data as Recipient;
      setRecipient(nextRecipient);

      await resolveRecipientAvatar(nextRecipient);

      const orders = (ordersResult.data ?? []) as OrderRow[];
      setOrderCount(orders.length);
      setTotalAssistance(
        orders
          .filter(
            (order) => order.status !== 'failed' && order.status !== 'cancelled'
          )
          .reduce((sum, order) => sum + Number(order.amount ?? 0), 0)
      );
      setGroupedOrders(groupOrdersByDate(orders));
      setCareAlerts((careAlertsResult.data ?? []) as CareAlertRow[]);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    const [recipientResult, ordersResult, careAlertsResult] = await Promise.all(
      [
        supabase
          .from('recipients')
          .select(
            'id,first_name,last_name,relationship,country,city,mobile_number,photo_path'
          )
          .eq('id', id)
          .eq('user_id', user.id)
          .single(),
        supabase
          .from('support_orders')
          .select(
            'id,service_type,status,amount,created_at,merchant_id,merchants(name)'
          )
          .eq('recipient_id', id)
          .eq('user_id', user.id)
          .order('created_at', { ascending: false }),
        supabase
          .from('care_alerts')
          .select('id,title,body,severity,service_type,due_at')
          .eq('recipient_id', id)
          .eq('user_id', user.id)
          .is('dismissed_at', null)
          .order('due_at', { ascending: true, nullsFirst: false })
          .limit(3),
      ]
    );

    const queryError =
      recipientResult.error ?? ordersResult.error ?? careAlertsResult.error;
    if (queryError || !recipientResult.data) {
      showError(queryError?.message ?? 'Loved one not found');
      setLoading(false);
      return;
    }

    const nextRecipient = recipientResult.data as Recipient;
    setRecipient(nextRecipient);

    await resolveRecipientAvatar(nextRecipient);

    const orders = (ordersResult.data ?? []) as OrderRow[];
    setOrderCount(orders.length);
    setTotalAssistance(
      orders
        .filter(
          (order) => order.status !== 'failed' && order.status !== 'cancelled'
        )
        .reduce((sum, order) => sum + Number(order.amount ?? 0), 0)
    );
    setGroupedOrders(groupOrdersByDate(orders));
    setCareAlerts((careAlertsResult.data ?? []) as CareAlertRow[]);
    setLoading(false);
  };

  const formatDueDate = (value: string | null) => {
    if (!value) return 'Upcoming';
    const dueDate = new Date(value);
    const now = new Date();
    const diffMs = dueDate.getTime() - now.getTime();
    const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays <= 0) return 'Due today';
    if (diffDays === 1) return 'Due tomorrow';
    if (diffDays <= 5) return `Due in ${diffDays} days`;

    return 'Due in 5 days';
  };

  const normalizeVoucherStatus = (
    serviceType: string | null,
    status: string | null
  ) => {
    const normalizedStatus = (status ?? '').toLowerCase();
    if (serviceType === 'grocery' || serviceType === 'medication') {
      if (normalizedStatus === 'redeemed') return 'redeemed';
      if (normalizedStatus === 'partial') return 'partial';
      return 'created';
    }
    return normalizedStatus || 'created';
  };

  const formatSupportDateTime = (value: string) =>
    new Date(value).toLocaleString(undefined, {
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    });

  const getStatusDescription = (order: OrderRow) => {
    const normalizedStatus = normalizeVoucherStatus(
      order.service_type,
      order.status
    );
    const serviceLabel = order.service_type.replace(/_/g, ' ');

    if (
      order.service_type === 'grocery' ||
      order.service_type === 'medication'
    ) {
      if (normalizedStatus === 'redeemed') {
        return 'Voucher collected by recipient.';
      }
      if (normalizedStatus === 'partial') {
        return 'Voucher partially used at merchant.';
      }
      return 'Voucher created and ready to share.';
    }

    if (order.service_type === 'airtime') {
      if (normalizedStatus === 'completed') {
        return 'Top-up confirmed on recipient line.';
      }
      if (normalizedStatus === 'delivered') {
        return 'Top-up sent and awaiting final confirmation.';
      }
      return `${serviceLabel.charAt(0).toUpperCase() + serviceLabel.slice(1)} request in progress.`;
    }

    if (order.service_type === 'electricity') {
      if (normalizedStatus === 'completed') {
        return 'Token delivered successfully.';
      }
      return 'Electricity support is being processed.';
    }

    return 'Support action recorded successfully.';
  };

  const handleShareVoucher = async (order: OrderRow) => {
    if (
      order.service_type !== 'grocery' &&
      order.service_type !== 'medication'
    ) {
      return;
    }

    const serviceLabel =
      order.service_type === 'grocery'
        ? 'grocery voucher'
        : 'medication voucher';
    const recipientName = recipient?.first_name ?? 'your loved one';
    const merchantName = order.merchants?.name ?? 'participating merchants';
    const statusLabel = normalizeVoucherStatus(
      order.service_type,
      order.status
    );
    const shareText =
      statusLabel === 'redeemed'
        ? `${recipientName}'s ${serviceLabel} from Kumusha has already been redeemed at ${merchantName}.`
        : `Hi ${recipientName}, your ${serviceLabel} from Kumusha is ready to use at participating merchants. Reference: ${order.id}.`;

    if (navigator.share) {
      try {
        await navigator.share({
          title: 'Kumusha voucher',
          text: shareText,
        });
        return;
      } catch {
        return;
      }
    }

    try {
      await navigator.clipboard.writeText(shareText);
    } catch {
      showError('Sharing is not available on this device.');
      return;
    }
  };

  const getServiceTheme = (
    serviceType: string | null,
    status?: string | null
  ) => {
    const normalizedStatus = normalizeVoucherStatus(
      serviceType,
      status ?? null
    );
    const successLike = ['redeemed', 'completed'];
    const pendingLike = ['created', 'delivered', 'processing'];
    const partialLike = ['partial'];

    const resolveTrailingIcon = () => {
      if (partialLike.includes(normalizedStatus)) return alertCircleOutline;
      if (successLike.includes(normalizedStatus)) return checkmarkCircleOutline;
      if (pendingLike.includes(normalizedStatus)) return timeOutline;
      return timeOutline;
    };

    switch (serviceType) {
      case 'grocery':
        return {
          icon: cartOutline,
          cardClass: 'service-grocery',
          statusClass:
            normalizedStatus === 'partial'
              ? 'status-partial'
              : normalizedStatus === 'created'
                ? 'status-created'
                : 'status-redeemed',
          trailingIcon: resolveTrailingIcon(),
        };
      case 'medication':
        return {
          icon: medkitOutline,
          cardClass: 'service-medication',
          statusClass:
            normalizedStatus === 'partial'
              ? 'status-partial'
              : normalizedStatus === 'created'
                ? 'status-created'
                : 'status-redeemed',
          trailingIcon: resolveTrailingIcon(),
        };
      case 'electricity':
        return {
          icon: flashOutline,
          cardClass: 'service-electricity',
          statusClass:
            normalizedStatus === 'completed'
              ? 'status-completed'
              : 'status-pending',
          trailingIcon: resolveTrailingIcon(),
        };
      case 'airtime':
        return {
          icon: wifiOutline,
          cardClass: 'service-airtime',
          statusClass:
            normalizedStatus === 'completed'
              ? 'status-completed'
              : 'status-pending',
          trailingIcon: resolveTrailingIcon(),
        };
      default:
        return {
          icon: alertCircleOutline,
          cardClass: 'service-default',
          statusClass: 'status-default',
          trailingIcon: resolveTrailingIcon(),
        };
    }
  };

  const renderServiceIcon = (serviceType: string | null, ionIcon: string) => {
    if (serviceType === 'grocery') {
      return (
        <img
          src={basketIcon}
          alt=""
          className="recipient-custom-basket-icon"
          style={{ width: 33, height: 33, objectFit: 'contain' }}
        />
      );
    }
    return <IonIcon icon={ionIcon} />;
  };

  const handleOpenOrder = (orderId?: string | null) => {
    if (orderId) history.push(`/orders/${orderId}`);
  };

  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="recipients-back-button"
              fill="clear"
              onClick={() =>
                history.length > 1
                  ? history.goBack()
                  : history.replace('/recipients')
              }
              aria-label="Go back"
            >
              <IonIcon icon={chevronBackOutline} slot="icon-only" />
            </IonButton>
          </IonButtons>
          <IonTitle style={{ fontSize: '18px', fontWeight: 700 }}>
            {recipient
              ? `${recipient.first_name} ${recipient.last_name}`.trim()
              : 'Loved one'}
          </IonTitle>
          <IonButtons slot="end">
            <IonButton
              fill="clear"
              onClick={() => history.push(`/recipients/${id}/edit`)}
              aria-label="Edit recipient"
            >
              <IonIcon icon={createOutline} slot="icon-only" />
            </IonButton>
          </IonButtons>
        </IonToolbar>
      </IonHeader>

      <IonContent
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-bottom': 'calc(40px + var(--ion-safe-area-bottom, 0px))',
          } as React.CSSProperties
        }
      >
        {loading ? (
          <div className="recipient-summary-card">
            <IonSkeletonText
              animated
              style={{ width: 80, height: 80, borderRadius: 24 }}
            />
            <IonSkeletonText animated style={{ width: '50%', height: 22 }} />
            <IonSkeletonText animated style={{ width: '70%', height: 14 }} />
          </div>
        ) : recipient ? (
          <>
            {error && (
              <p
                style={{ margin: '12px 20px', color: '#dc2626', fontSize: 13 }}
              >
                {error}
              </p>
            )}
            <div className="recipient-summary-card">
              {avatarUrl ? (
                <img
                  src={avatarUrl}
                  alt={recipient.first_name}
                  className="rsc-avatar"
                />
              ) : (
                <div className="rsc-avatar-placeholder">
                  {recipient.first_name.charAt(0)}
                </div>
              )}
              <div className="rsc-info">
                <h1 className="rsc-name">
                  {recipient.first_name} {recipient.last_name}
                </h1>
                <p className="rsc-relationship">{recipient.relationship}</p>
                <p className="rsc-location">
                  {recipient.city}, {recipient.country}
                </p>
                <p className="rsc-location">{recipient.mobile_number}</p>
              </div>
              <div className="rsc-stats-row">
                <div className="rsc-stat-box">
                  <p className="rsc-stat-val">${Math.round(totalAssistance)}</p>
                  <p className="rsc-stat-label">Total sent</p>
                </div>
                <div className="rsc-stat-box">
                  <p className="rsc-stat-val">{orderCount}</p>
                  <p className="rsc-stat-label">Orders</p>
                </div>
              </div>
              <IonButton
                className="rsc-cta-btn"
                onClick={() =>
                  history.push('/support/new', { recipientId: id })
                }
              >
                <IonIcon icon={heartOutline} slot="start" />
                Send support
              </IonButton>
            </div>

            <h2 className="detail-section-header">Care alerts</h2>
            {careAlerts.length === 0 ? (
              <div className="recipient-empty-inline-card">
                <div className="recipient-empty-inline-icon">
                  <IonIcon icon={timeOutline} />
                </div>
                <div className="recipient-empty-inline-copy">
                  <h3>No active alerts</h3>
                  <p>
                    This loved one has no upcoming care reminders right now.
                  </p>
                </div>
              </div>
            ) : (
              <div className="recipient-alerts-stack">
                {careAlerts.map((alert) => {
                  const theme = getServiceTheme(alert.service_type);
                  return (
                    <button
                      key={alert.id}
                      type="button"
                      className={`recipient-alert-card ${theme.cardClass}`}
                      onClick={() =>
                        history.push('/support/new', {
                          recipientId: id,
                          serviceType: alert.service_type,
                        })
                      }
                      style={{
                        width: '100%',
                        textAlign: 'left',
                        border: 'none',
                      }}
                    >
                      <div
                        className={`recipient-alert-icon-wrap ${theme.cardClass}`}
                      >
                        {renderServiceIcon(alert.service_type, theme.icon)}
                      </div>
                      <div className="recipient-alert-copy">
                        <div className="recipient-alert-topline">
                          <h3>{alert.title}</h3>
                          <span
                            className={`recipient-alert-pill ${theme.statusClass}`}
                          >
                            {formatDueDate(alert.due_at)}
                          </span>
                        </div>
                        <p>{alert.body}</p>
                      </div>
                    </button>
                  );
                })}
              </div>
            )}

            <div className="detail-section-header detail-section-header-with-meta">
              <div>
                <h2>Support history</h2>
                <p>{orderCount} recent care actions</p>
              </div>
            </div>
            {groupedOrders.length === 0 ? (
              <div className="empty-state-card">
                <IonIcon icon={heartOutline} className="esc-icon" />
                <h3 className="esc-title">No support yet</h3>
                <p className="esc-msg">
                  Send first support and history will appear here.
                </p>
                <IonButton
                  onClick={() =>
                    history.push('/support/new', { recipientId: id })
                  }
                  style={
                    {
                      '--background': '#6d28d9',
                      '--border-radius': '999px',
                      '--box-shadow': 'none',
                    } as React.CSSProperties
                  }
                >
                  Send first support
                </IonButton>
              </div>
            ) : (
              <div className="recipient-history-stack">
                {groupedOrders.map((group) => (
                  <div
                    key={group.label}
                    style={{
                      display: 'flex',
                      flexDirection: 'column',
                      gap: '10px',
                    }}
                  >
                    <div className="recipient-history-date-label">
                      {group.label}
                    </div>
                    {group.items.map((row) => {
                      const inferredServiceType = row.service_type;
                      const normalizedStatus = normalizeVoucherStatus(
                        inferredServiceType,
                        row.status
                      );
                      const theme = getServiceTheme(
                        inferredServiceType,
                        normalizedStatus
                      );
                      const displayTitle =
                        row.service_type === 'grocery'
                          ? 'Grocery voucher'
                          : row.service_type === 'medication'
                            ? 'Medication voucher'
                            : row.service_type === 'electricity'
                              ? 'Electricity'
                              : row.service_type === 'airtime'
                                ? 'Airtime'
                                : `${row.service_type.charAt(0).toUpperCase()}${row.service_type.slice(1)}`;
                      const merchantName = row.merchants?.name ?? null;
                      const voucherSendDisabled =
                        (row.service_type === 'grocery' ||
                          row.service_type === 'medication') &&
                        normalizedStatus === 'redeemed';
                      return (
                        <button
                          key={row.id}
                          type="button"
                          className={`recipient-history-item ${theme.cardClass}`}
                          onClick={() => handleOpenOrder(row.id)}
                        >
                          <div
                            className={`recipient-history-badge ${theme.cardClass}`}
                          >
                            {renderServiceIcon(inferredServiceType, theme.icon)}
                          </div>
                          <div className="recipient-history-copy">
                            <div className="recipient-history-topline">
                              <div className="recipient-history-title-block">
                                <h3>{displayTitle}</h3>
                                {((row.service_type === 'grocery' ||
                                  row.service_type === 'medication') &&
                                  (normalizedStatus === 'redeemed' ||
                                    normalizedStatus === 'partial') &&
                                  merchantName) ||
                                (row.service_type !== 'grocery' &&
                                  row.service_type !== 'medication') ? (
                                  <p className="recipient-history-support-meta">
                                    {row.service_type === 'grocery' ||
                                    row.service_type === 'medication'
                                      ? merchantName
                                      : (merchantName ??
                                        formatSupportDateTime(row.created_at))}
                                  </p>
                                ) : null}
                              </div>
                              {row.amount !== null &&
                              row.amount !== undefined ? (
                                <span className="recipient-history-amount">
                                  ${Number(row.amount).toFixed(2)}
                                </span>
                              ) : null}
                            </div>
                            <div className="recipient-history-meta-row recipient-history-meta-row-compact">
                              <span
                                className={`recipient-history-status ${theme.statusClass}`}
                              >
                                {normalizedStatus.replace(/_/g, ' ')}
                              </span>
                              <IonIcon
                                icon={theme.trailingIcon}
                                className={`recipient-history-trailing ${theme.statusClass}`}
                              />
                            </div>
                            {(row.service_type === 'grocery' ||
                              row.service_type === 'medication') && (
                              <div className="recipient-history-details-grid">
                                <div className="recipient-history-detail-chip">
                                  <span className="recipient-history-detail-label">
                                    Last updated
                                  </span>
                                  <span className="recipient-history-detail-value">
                                    {formatSupportDateTime(row.created_at)}
                                  </span>
                                </div>
                                <button
                                  type="button"
                                  className={`recipient-history-share-chip ${theme.cardClass} ${voucherSendDisabled ? 'is-disabled' : ''}`}
                                  onClick={(event) => {
                                    event.stopPropagation();
                                    if (voucherSendDisabled) return;
                                    void handleShareVoucher(row);
                                  }}
                                  disabled={voucherSendDisabled}
                                  aria-disabled={voucherSendDisabled}
                                >
                                  <IonIcon icon={paperPlaneOutline} />
                                  <div className="recipient-history-share-copy">
                                    <span className="recipient-history-detail-label">
                                      Share
                                    </span>
                                    <span className="recipient-history-detail-value">
                                      Send voucher
                                    </span>
                                  </div>
                                </button>
                              </div>
                            )}
                            <p className="recipient-history-description">
                              {getStatusDescription(row)}
                            </p>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                ))}
              </div>
            )}
          </>
        ) : null}
      </IonContent>
    </IonPage>
  );
};

export default RecipientDetailPage;
