import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { AppLayout } from '@/components/AppLayout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { formatIDR, formatDateTime } from '@/lib/format';
import { Eye, CheckCircle, XCircle } from 'lucide-react';
import { toast } from '@/hooks/use-toast';

interface Order {
  id: string;
  user_id: string;
  total_amount: number;
  status: string;
  payment_status: string | null;
  payment_method: string | null;
  payment_reference: string | null;
  created_at: string;
  profile?: { email: string } | null;
}

interface OrderItem {
  id: string;
  product: { title: string };
  unit_price: number;
  quantity: number;
}

export default function AdminOrders() {
  const { user, isAdmin, loading: authLoading } = useAuth();
  const navigate = useNavigate();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [dialogOpen, setDialogOpen] = useState(false);

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

  const fetchOrders = async () => {
    const { data, error } = await supabase
      .from('orders')
      .select('*, profile:profiles(email)')
      .order('created_at', { ascending: false });
    if (!error && data) setOrders(data as unknown as Order[]);
    setLoading(false);
  };

  const viewOrderDetails = async (order: Order) => {
    setSelectedOrder(order);
    const { data } = await supabase
      .from('order_items')
      .select('*, product:products(title)')
      .eq('order_id', order.id);
    setOrderItems(data as unknown as OrderItem[] || []);
    setDialogOpen(true);
  };

  const updateOrderStatus = async (orderId: string, status: 'paid' | 'cancelled') => {
    const { error } = await supabase.from('orders').update({ payment_status: status }).eq('id', orderId);
    if (error) {
      toast({ title: 'Error', description: 'Gagal update status', variant: 'destructive' });
    } else {
      if (status === 'paid') {
        // Grant access for each order item
        const { data: items } = await supabase.from('order_items').select('product_id').eq('order_id', orderId);
        const order = orders.find(o => o.id === orderId);
        if (items && order) {
          for (const item of items) {
            await supabase.from('user_access').upsert({
              user_id: order.user_id,
              product_id: item.product_id,
              granted_at: new Date().toISOString(),
            }, { onConflict: 'user_id,product_id' });
          }
        }
      }
      toast({ title: 'Berhasil', description: `Status diubah ke ${status}` });
      fetchOrders();
      setDialogOpen(false);
    }
  };

  const getStatusBadge = (status: string | null) => {
    switch (status) {
      case 'paid': return <Badge className="bg-accent">Lunas</Badge>;
      case 'pending': return <Badge className="bg-secondary">Pending</Badge>;
      case 'cancelled': return <Badge className="bg-destructive">Dibatalkan</Badge>;
      default: return <Badge className="bg-muted">{status}</Badge>;
    }
  };

  if (authLoading || loading) {
    return (
      <AppLayout>
        <div className="container mx-auto px-4 py-8">
          <Skeleton className="h-10 w-1/3 mb-8" />
          <Skeleton className="h-64 w-full" />
        </div>
      </AppLayout>
    );
  }

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

        <Card className="border-2 border-border">
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID Order</TableHead>
                  <TableHead>Email</TableHead>
                  <TableHead>Total</TableHead>
                  <TableHead>Metode</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Tanggal</TableHead>
                  <TableHead className="text-right">Aksi</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {orders.map((order) => (
                  <TableRow key={order.id}>
                    <TableCell className="font-mono text-sm">{order.id.slice(0, 8)}</TableCell>
                    <TableCell>{order.profile?.email || '-'}</TableCell>
                    <TableCell className="font-bold">{formatIDR(order.total_amount)}</TableCell>
                    <TableCell className="uppercase text-sm">{order.payment_method || '-'}</TableCell>
                    <TableCell>{getStatusBadge(order.payment_status)}</TableCell>
                    <TableCell>{formatDateTime(order.created_at)}</TableCell>
                    <TableCell className="text-right">
                      <Button variant="ghost" size="sm" onClick={() => viewOrderDetails(order)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
                {orders.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                      Belum ada order
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="max-w-lg border-2 border-border">
            <DialogHeader>
              <DialogTitle>Detail Order</DialogTitle>
            </DialogHeader>
            {selectedOrder && (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-muted-foreground">ID:</span> {selectedOrder.id.slice(0, 8)}</div>
                  <div><span className="text-muted-foreground">Referensi:</span> {selectedOrder.payment_reference || '-'}</div>
                  <div><span className="text-muted-foreground">Email:</span> {selectedOrder.profile?.email}</div>
                  <div><span className="text-muted-foreground">Metode:</span> {selectedOrder.payment_method || '-'}</div>
                </div>
                <div className="border-t border-border pt-4">
                  <p className="font-medium mb-2">Item:</p>
                  {orderItems.map((item) => (
                    <div key={item.id} className="flex justify-between py-1">
                      <span>{item.product?.title}</span>
                      <span className="font-bold">{formatIDR(item.unit_price)}</span>
                    </div>
                  ))}
                  <div className="flex justify-between pt-2 border-t border-border mt-2">
                    <span className="font-bold">Total</span>
                    <span className="font-bold">{formatIDR(selectedOrder.total_amount)}</span>
                  </div>
                </div>
                <div className="flex gap-2 pt-4">
                  {selectedOrder.payment_status !== 'paid' && (
                    <Button onClick={() => updateOrderStatus(selectedOrder.id, 'paid')} className="flex-1">
                      <CheckCircle className="w-4 h-4 mr-2" />
                      Tandai Lunas
                    </Button>
                  )}
                  {selectedOrder.payment_status !== 'cancelled' && (
                    <Button variant="outline" onClick={() => updateOrderStatus(selectedOrder.id, 'cancelled')} className="flex-1 border-2">
                      <XCircle className="w-4 h-4 mr-2" />
                      Batalkan
                    </Button>
                  )}
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </AppLayout>
  );
}
