import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { AppLayout } from '@/components/AppLayout';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { formatIDR, formatDate } from '@/lib/format';

interface Order {
  id: string;
  total_amount: number;
  status: string;
  payment_status: string | null;
  payment_method: string | null;
  created_at: string;
}

export default function MemberOrders() {
  const { user, loading: authLoading } = useAuth();
  const navigate = useNavigate();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!authLoading && !user) navigate('/auth');
    else if (user) fetchOrders();
  }, [user, authLoading]);

  const fetchOrders = async () => {
    const { data } = await supabase
      .from('orders')
      .select('*')
      .eq('user_id', user!.id)
      .order('created_at', { ascending: false });
    if (data) setOrders(data);
    setLoading(false);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'paid': return 'bg-accent';
      case 'pending': return 'bg-secondary';
      case 'cancelled': return 'bg-destructive';
      default: return 'bg-secondary';
    }
  };

  const getPaymentStatusLabel = (status: string | null) => {
    switch (status) {
      case 'paid': return 'Lunas';
      case 'pending': return 'Menunggu Pembayaran';
      case 'failed': return 'Gagal';
      case 'cancelled': return 'Dibatalkan';
      default: return status || 'Pending';
    }
  };

  if (authLoading || loading) {
    return (
      <AppLayout>
        <div className="container mx-auto px-4 py-8">
          <Skeleton className="h-10 w-1/3 mb-8" />
          <div className="space-y-4">
            {[...Array(3)].map((_, i) => <Skeleton key={i} className="h-24" />)}
          </div>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold mb-2">Riwayat Order</h1>
        <p className="text-muted-foreground mb-8">Semua pesanan Anda</p>

        {orders.length === 0 ? (
          <Card className="border-2 border-border">
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground">Belum ada order</p>
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-4">
            {orders.map((order) => (
              <Card key={order.id} className="border-2 border-border">
                <CardContent className="py-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-mono text-sm text-muted-foreground">{order.id.slice(0, 8)}</p>
                      <p className="text-sm text-muted-foreground">{formatDate(order.created_at)}</p>
                      {order.payment_method && (
                        <p className="text-xs text-muted-foreground uppercase">{order.payment_method}</p>
                      )}
                    </div>
                    <div className="flex items-center gap-4">
                      <Badge className={getStatusColor(order.payment_status || order.status)}>
                        {getPaymentStatusLabel(order.payment_status || order.status)}
                      </Badge>
                      <span className="font-bold">{formatIDR(order.total_amount)}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
