import React, { useMemo, useState } from 'react';
import {
  IonContent,
  IonIcon,
  IonPage,
  IonRefresher,
  IonRefresherContent,
  IonSkeletonText,
  useIonViewWillEnter,
} from '@ionic/react';
import { receiptOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import ListSearchRow from '../components/ListSearchRow';
import OrderSummaryCard, { OrderSummary } from '../components/OrderSummaryCard';
import '../styles/support.css';
import '../styles/recipients.css';

type OrderRow = {
  id: string;
  service_type: string;
  amount: number;
  status: string;
  created_at: string;
  recipient_id: string;
  merchant_id: string | null;
  recipients?: {
    first_name: string;
    last_name: string;
    photo_path: string | null;
  } | null;
  merchants?: { name: string; branch_name: string | null } | null;
};

const statusFilters = [
  { value: 'all', label: 'All' },
  { value: 'paid', label: 'Paid' },
  { value: 'ready_for_redemption', label: 'Ready' },
  { value: 'redeemed', label: 'Redeemed' },
  { value: 'delivered', label: 'Delivered' },
  { value: 'expired', label: 'Expired' },
];

const OrdersPage: React.FC = () => {
  const history = useHistory();
  const { user } = useAuth();
  const [orders, setOrders] = useState<OrderSummary[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [activeStatus, setActiveStatus] = useState('all');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  const loadOrders = async () => {
    if (!user) return;
    setLoading(true);
    setError(null);

    const { data, error: ordersError } = await supabase
      .from('support_orders')
      .select(
        'id,service_type,amount,status,created_at,recipient_id,merchant_id,recipients(first_name,last_name,photo_path),merchants(name,branch_name)'
      )
      .eq('user_id', user.id)
      .order('created_at', { ascending: false });

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

    const rows = (data ?? []) as unknown as OrderRow[];
    const normalized = await Promise.all(
      rows.map(async (row) => {
        const recipientName = row.recipients
          ? `${row.recipients.first_name} ${row.recipients.last_name}`
          : 'Loved one';
        const avatarUrl = row.recipients?.photo_path
          ? ((
              await supabase.storage
                .from('recipient-photos')
                .createSignedUrl(row.recipients.photo_path, 3600)
            ).data?.signedUrl ?? null)
          : null;

        return {
          id: row.id,
          recipientName,
          serviceType:
            row.service_type.charAt(0).toUpperCase() +
            row.service_type.slice(1),
          merchantName: row.merchants
            ? `${row.merchants.name}${row.merchants.branch_name ? ` — ${row.merchants.branch_name}` : ''}`
            : undefined,
          amount: Number(row.amount ?? 0),
          status: row.status,
          createdAt: row.created_at,
          avatarUrl,
        };
      })
    );

    setOrders(normalized);
    setLoading(false);
  };

  const visibleOrders = useMemo(() => {
    const query = searchTerm.trim().toLowerCase();
    return orders.filter((order) => {
      const statusMatch =
        activeStatus === 'all' || order.status === activeStatus;
      const searchMatch =
        !query ||
        [
          order.recipientName,
          order.serviceType,
          order.merchantName,
          order.status,
        ]
          .join(' ')
          .toLowerCase()
          .includes(query);
      return statusMatch && searchMatch;
    });
  }, [orders, activeStatus, searchTerm]);

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

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonContent
        fullscreen
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-start': '0px',
            '--padding-end': '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">Activity</h1>
            <p className="rlc-location" style={{ marginTop: 4 }}>
              {orders.length} support updates
            </p>
          </div>
        </div>

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

        <div className="orders-filter-row">
          {statusFilters.map((filter) => (
            <button
              key={filter.value}
              type="button"
              className={`status-filter-chip ${activeStatus === filter.value ? 'active' : 'inactive'}`}
              onClick={() => setActiveStatus(filter.value)}
              style={{ border: 'none' }}
            >
              {filter.label}
            </button>
          ))}
        </div>

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

        {loading ? (
          <div>
            {[1, 2, 3].map((item) => (
              <div key={item} className="order-summary-card">
                <IonSkeletonText
                  animated
                  style={{
                    width: 48,
                    height: 48,
                    borderRadius: 16,
                    flexShrink: 0,
                  }}
                />
                <div style={{ flex: 1 }}>
                  <IonSkeletonText
                    animated
                    style={{ width: '70%', height: 15 }}
                  />
                  <IonSkeletonText
                    animated
                    style={{ width: '45%', height: 12 }}
                  />
                </div>
              </div>
            ))}
          </div>
        ) : visibleOrders.length === 0 ? (
          <div className="empty-state-card">
            <IonIcon icon={receiptOutline} className="esc-icon" />
            <h2 className="esc-title">
              {orders.length === 0 ? 'No orders yet' : 'No matching orders'}
            </h2>
            <p className="esc-msg">
              {orders.length === 0
                ? 'Your support transactions will appear here.'
                : 'Try changing your search or status filter.'}
            </p>
          </div>
        ) : (
          <div>
            {visibleOrders.map((order) => (
              <OrderSummaryCard
                key={order.id}
                order={order}
                onClick={(id) => history.push(`/orders/${id}`)}
              />
            ))}
          </div>
        )}
      </IonContent>
    </IonPage>
  );
};

export default OrdersPage;
