import React, { useState } from 'react';
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonIcon,
  IonPage,
  IonSkeletonText,
  IonTitle,
  IonToolbar,
  useIonViewWillEnter,
} from '@ionic/react';
import {
  chevronBackOutline,
  copyOutline,
  qrCodeOutline,
  shieldCheckmarkOutline,
} from 'ionicons/icons';
import { useHistory, useParams } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import '../styles/support.css';

type Params = { id: string };

type RedemptionEntry = {
  id: string;
  redeemed_amount: number;
  redeemed_at: string;
  merchant_name: string | null;
  status: string | null;
};

type Voucher = {
  id: string;
  voucher_code: string;
  status: string;
  expires_at: string;
  qr_payload: string;
  voucher_type: string;
  redeemed_amount?: number;
  remaining_amount?: number;
  voucher_redemptions?: RedemptionEntry[] | null;
  support_orders?: {
    service_type: string;
    amount: number;
    recipients?: { first_name: string; last_name: string } | null;
    merchants?: { name: string; branch_name: string | null } | null;
  } | null;
};

const VoucherDetailPage: React.FC = () => {
  const { id } = useParams<Params>();
  const history = useHistory();
  const { user } = useAuth();
  const [voucher, setVoucher] = useState<Voucher | null>(null);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState<string | null>(null);

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

  const showMessage = (text: string) => {
    setMessage(text);
    setTimeout(() => setMessage(null), 4000);
  };

  const loadVoucher = async () => {
    if (!user) return;
    setLoading(true);

    const { data, error } = await supabase
      .from('vouchers')
      .select(
        'id,voucher_code,status,expires_at,qr_payload,voucher_type,redeemed_amount,remaining_amount,voucher_redemptions(id,redeemed_amount,redeemed_at,merchant_name,status),support_orders!inner(service_type,amount,user_id,recipients(first_name,last_name),merchants(name,branch_name))'
      )
      .eq('id', id)
      .eq('support_orders.user_id', user.id)
      .single();

    if (error || !data) {
      showMessage(error?.message ?? 'Voucher not found');
      setLoading(false);
      return;
    }

    setVoucher(data as unknown as Voucher);
    setLoading(false);
  };

  const handleCopyCode = async () => {
    if (!voucher) return;
    await navigator.clipboard.writeText(voucher.voucher_code);
    showMessage('Voucher code copied');
  };

  const totalAmount = Number(voucher?.support_orders?.amount ?? 0);
  const redeemedAmount = Number(voucher?.redeemed_amount ?? 0);
  const fallbackRemaining = Math.max(totalAmount - redeemedAmount, 0);
  const remainingAmount = Number(
    voucher?.remaining_amount ?? fallbackRemaining
  );
  const hasPartialRedemption = redeemedAmount > 0 && remainingAmount > 0;
  const redemptionHistory = [...(voucher?.voucher_redemptions ?? [])].sort(
    (a, b) =>
      new Date(b.redeemed_at).getTime() - new Date(a.redeemed_at).getTime()
  );

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

      <IonContent
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
          } as React.CSSProperties
        }
      >
        {loading ? (
          <div className="voucher-hero-card">
            <IonSkeletonText
              animated
              style={{ width: 160, height: 32, borderRadius: 999 }}
            />
            <IonSkeletonText
              animated
              style={{ width: 220, height: 220, borderRadius: 24 }}
            />
          </div>
        ) : voucher ? (
          <>
            {message && (
              <p
                style={{ margin: '12px 20px', color: '#6d28d9', fontSize: 13 }}
              >
                {message}
              </p>
            )}
            <div className="voucher-hero-card">
              <span className="vhc-code-pill">{voucher.voucher_code}</span>
              <div className="vhc-qr-placeholder">
                <IonIcon icon={qrCodeOutline} />
              </div>
              <div>
                <p className="vhc-expiry">
                  Expires {new Date(voucher.expires_at).toLocaleDateString()}
                </p>
                <p className="vhc-merchant">
                  {voucher.support_orders?.merchants
                    ? `${voucher.support_orders.merchants.name}${voucher.support_orders.merchants.branch_name ? ` — ${voucher.support_orders.merchants.branch_name}` : ''}`
                    : `Kumusha ${voucher.support_orders?.service_type === 'medication' ? 'pharmacy' : 'grocery'} partner`}
                </p>
                <p className="vhc-merchant">
                  For{' '}
                  {voucher.support_orders?.recipients
                    ? `${voucher.support_orders.recipients.first_name} ${voucher.support_orders.recipients.last_name}`
                    : 'recipient'}{' '}
                  · ${Number(voucher.support_orders?.amount ?? 0).toFixed(2)}
                </p>
              </div>
              <IonButton
                onClick={handleCopyCode}
                style={
                  {
                    '--background': '#6d28d9',
                    '--border-radius': '999px',
                    '--box-shadow': 'none',
                  } as React.CSSProperties
                }
              >
                <IonIcon icon={copyOutline} slot="start" />
                Copy code
              </IonButton>
            </div>

            {(hasPartialRedemption || redemptionHistory.length > 0) && (
              <div className="voucher-balance-card">
                <div className="voucher-balance-head">
                  <div>
                    <p className="voucher-balance-title">Voucher balance</p>
                    <p className="voucher-balance-subtitle">
                      Track redeemed and remaining value for this voucher.
                    </p>
                  </div>
                  <div className="voucher-balance-total">
                    ${totalAmount.toFixed(2)}
                  </div>
                </div>

                <div className="voucher-balance-pills">
                  <div className="voucher-balance-pill is-redeemed">
                    Redeemed ${redeemedAmount.toFixed(2)}
                  </div>
                  <div className="voucher-balance-pill is-remaining">
                    Unredeemed ${remainingAmount.toFixed(2)}
                  </div>
                </div>

                {redemptionHistory.length > 0 && (
                  <div className="voucher-redemption-history">
                    <p className="voucher-redemption-history-title">
                      Redemption history
                    </p>
                    {redemptionHistory.map((entry) => (
                      <div key={entry.id} className="voucher-redemption-row">
                        <div>
                          <p className="voucher-redemption-merchant">
                            {entry.merchant_name ||
                              voucher.support_orders?.merchants?.name ||
                              `Kumusha ${voucher.support_orders?.service_type === 'medication' ? 'pharmacy' : 'grocery'} partner`}
                          </p>
                          <p className="voucher-redemption-date">
                            {new Date(entry.redeemed_at).toLocaleString()}
                          </p>
                        </div>
                        <div className="voucher-redemption-right">
                          <p className="voucher-redemption-amount">
                            ${entry.redeemed_amount.toFixed(2)}
                          </p>
                          <span className="voucher-redemption-status">
                            {entry.status || 'Redeemed'}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            <div className="security-note-card">
              <IonIcon icon={shieldCheckmarkOutline} className="snc-icon" />
              <p className="snc-text">
                Redeemable at any approved Kumusha{' '}
                {voucher.support_orders?.service_type === 'medication'
                  ? 'pharmacy'
                  : 'grocery'}{' '}
                partner. Balance updates automatically after partial redemption.
                Do not share code.
              </p>
            </div>
          </>
        ) : null}
      </IonContent>
    </IonPage>
  );
};

export default VoucherDetailPage;
