import { logger } from '@/lib/logger';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { AdminLayout } from '@/components/admin/AdminLayout';
import { AdminPageHeader } from '@/components/admin/AdminPageHeader';
import { AdminPageContainer } from '@/components/admin/AdminPageContainer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { Package, Eye, RefreshCw, ShoppingBag, TrendingUp, Clock, CheckCircle, Mail, Loader2, UserSearch, X } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import { useNavigate } from 'react-router-dom';
import type { Tables } from '@/integrations/supabase/types';
import { FulfillmentStepper } from '@/components/admin/orders/FulfillmentStepper';
import { FulfillmentActions } from '@/components/admin/orders/FulfillmentActions';
import { EntityActivityTimeline } from '@/components/admin/EntityActivityTimeline';
import { EntityTags } from '@/components/admin/EntityTags';
import { EntityFollowers } from '@/components/admin/EntityFollowers';
import { SavedViewsMenu } from '@/components/admin/SavedViewsMenu';

type Order = Tables<'orders'>;
type OrderItem = Tables<'order_items'>;

const STATUS_LABELS: Record<string, string> = {
  pending: 'Pending',
  paid: 'Paid',
  shipped: 'Shipped',
  completed: 'Completed',
  cancelled: 'Cancelled',
  refunded: 'Refunded',
  failed: 'Failed',
};

const FULFILLMENT_LABELS: Record<string, string> = {
  unfulfilled: 'Unfulfilled',
  picked: 'Picked',
  packed: 'Packed',
  shipped: 'Shipped',
  delivered: 'Delivered',
};

const FULFILLMENT_COLORS: Record<string, string> = {
  unfulfilled: 'bg-muted text-muted-foreground',
  picked: 'bg-amber-500/10 text-amber-600 border-amber-500/20',
  packed: 'bg-blue-500/10 text-blue-600 border-blue-500/20',
  shipped: 'bg-indigo-500/10 text-indigo-600 border-indigo-500/20',
  delivered: 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20',
};

const STATUS_COLORS: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
  paid: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
  shipped: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
  completed: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200',
  cancelled: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
  refunded: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
  failed: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
};

export default function OrdersPage() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [activeViewId, setActiveViewId] = useState<string | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  const toggleId = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };
  const clearSelection = () => setSelectedIds(new Set());

  const bulkUpdateStatus = useMutation({
    mutationFn: async (status: string) => {
      const ids = Array.from(selectedIds);
      const { error } = await supabase.from('orders').update({ status }).in('id', ids);
      if (error) throw error;
      return ids.length;
    },
    onSuccess: (count, status) => {
      toast.success(`Updated ${count} order${count === 1 ? '' : 's'} to ${status}`);
      clearSelection();
      queryClient.invalidateQueries({ queryKey: ['orders'] });
    },
    onError: (e: Error) => toast.error(`Bulk update failed: ${e.message}`),
  });

  const { data: orders, isLoading } = useQuery({
    queryKey: ['orders', statusFilter],
    queryFn: async () => {
      let query = supabase
        .from('orders')
        .select('*')
        .order('created_at', { ascending: false });

      if (statusFilter !== 'all') {
        query = query.eq('status', statusFilter);
      }

      const { data, error } = await query;
      if (error) throw error;
      return data as Order[];
    },
  });

  const { data: orderItems } = useQuery({
    queryKey: ['order-items', selectedOrder?.id],
    queryFn: async () => {
      if (!selectedOrder) return [];
      const { data, error } = await supabase
        .from('order_items')
        .select('*')
        .eq('order_id', selectedOrder.id);
      if (error) throw error;
      return data as OrderItem[];
    },
    enabled: !!selectedOrder,
  });

  const updateStatusMutation = useMutation({
    mutationFn: async ({ orderId, status }: { orderId: string; status: string }) => {
      const { error } = await supabase
        .from('orders')
        .update({ status })
        .eq('id', orderId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] });
      toast.success('Order status updated');
    },
    onError: () => {
      toast.error('Could not update status');
    },
  });

  const sendConfirmationMutation = useMutation({
    mutationFn: async (orderId: string) => {
      const { error } = await supabase.functions.invoke('send-order-confirmation', {
        body: { orderId },
      });
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] });
      toast.success('Order confirmation sent');
    },
    onError: (error) => {
      logger.error('Failed to send confirmation:', error);
      toast.error('Could not send order confirmation');
    },
  });

  const formatPrice = (cents: number, currency: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency,
    }).format(cents / 100);
  };

  // Stats
  const stats = {
    total: orders?.length || 0,
    pending: orders?.filter(o => o.status === 'pending').length || 0,
    paid: orders?.filter(o => o.status === 'paid').length || 0,
    totalRevenue: orders
      ?.filter(o => o.status === 'paid' || o.status === 'completed')
      .reduce((sum, o) => sum + o.total_cents, 0) || 0,
  };

  return (
    <AdminLayout>
      <AdminPageContainer>
        <AdminPageHeader
          title="Orders"
          description="Manage and track customer orders"
        />

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Orders</CardTitle>
            <ShoppingBag className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pending</CardTitle>
            <Clock className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.pending}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Paid</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.paid}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Revenue</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatPrice(stats.totalRevenue, 'USD')}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card className="mb-6">
        <CardContent className="py-4">
          <div className="flex items-center gap-4">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Filter by status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Orders</SelectItem>
                <SelectItem value="pending">Pending</SelectItem>
                <SelectItem value="paid">Paid</SelectItem>
                <SelectItem value="shipped">Shipped</SelectItem>
                <SelectItem value="completed">Completed</SelectItem>
                <SelectItem value="cancelled">Cancelled</SelectItem>
                <SelectItem value="refunded">Refunded</SelectItem>
              </SelectContent>
            </Select>
            <Button
              variant="outline"
              size="sm"
              onClick={() => queryClient.invalidateQueries({ queryKey: ['orders'] })}
            >
              <RefreshCw className="h-4 w-4 mr-2" />
              Refresh
            </Button>
            <div className="ml-auto">
              <SavedViewsMenu
                scope="orders"
                currentConfig={{ statusFilter }}
                activeViewId={activeViewId}
                onActiveViewChange={setActiveViewId}
                onApply={(cfg) => {
                  if (typeof cfg.statusFilter === 'string') setStatusFilter(cfg.statusFilter);
                }}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Bulk Action Bar */}
      {selectedIds.size > 0 && (
        <Card className="border-primary/30 bg-primary/5">
          <CardContent className="flex flex-wrap items-center gap-3 py-3">
            <span className="text-sm font-medium">{selectedIds.size} selected</span>
            <Separator orientation="vertical" className="h-5" />
            <span className="text-xs text-muted-foreground">Set status:</span>
            <Select onValueChange={(v) => bulkUpdateStatus.mutate(v)} disabled={bulkUpdateStatus.isPending}>
              <SelectTrigger className="w-40 h-8">
                <SelectValue placeholder="Choose…" />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(STATUS_LABELS).map(([k, v]) => (
                  <SelectItem key={k} value={k}>{v}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <div className="ml-auto">
              <Button variant="ghost" size="sm" onClick={clearSelection}>
                <X className="h-4 w-4 mr-1" /> Clear
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Orders Table */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex items-center justify-center p-8">
              <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : orders?.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <Package className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>No orders found</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                 <TableRow>
                   <TableHead className="w-10">
                     <Checkbox
                       checked={
                         (orders?.length ?? 0) > 0 && orders!.every((o) => selectedIds.has(o.id))
                       }
                       onCheckedChange={(checked) => {
                         if (checked) setSelectedIds(new Set(orders!.map((o) => o.id)));
                         else clearSelection();
                       }}
                       aria-label="Select all"
                     />
                   </TableHead>
                   <TableHead>Order</TableHead>
                   <TableHead>Customer</TableHead>
                   <TableHead>Status</TableHead>
                   <TableHead>Fulfillment</TableHead>
                   <TableHead>Total</TableHead>
                   <TableHead>Date</TableHead>
                   <TableHead className="w-20"></TableHead>
                 </TableRow>
              </TableHeader>
              <TableBody>
                {orders?.map((order) => (
                  <TableRow key={order.id} data-state={selectedIds.has(order.id) ? 'selected' : undefined}>
                    <TableCell>
                      <Checkbox
                        checked={selectedIds.has(order.id)}
                        onCheckedChange={() => toggleId(order.id)}
                        aria-label={`Select order ${order.id.slice(0, 8)}`}
                      />
                    </TableCell>
                    <TableCell className="font-mono text-sm">
                      {order.id.slice(0, 8)}...
                    </TableCell>
                    <TableCell>
                      <div>
                        <p className="font-medium">{order.customer_name || 'Unknown'}</p>
                        <p className="text-sm text-muted-foreground">{order.customer_email}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={STATUS_COLORS[order.status] || ''}>
                        {STATUS_LABELS[order.status] || order.status}
                      </Badge>
                     </TableCell>
                     <TableCell>
                       <Badge className={FULFILLMENT_COLORS[(order as any).fulfillment_status] || 'bg-muted text-muted-foreground'}>
                         {FULFILLMENT_LABELS[(order as any).fulfillment_status] || 'Unfulfilled'}
                       </Badge>
                     </TableCell>
                     <TableCell className="font-medium">
                       {formatPrice(order.total_cents, order.currency)}
                     </TableCell>
                     <TableCell className="text-muted-foreground">
                       {format(new Date(order.created_at), 'PPp')}
                     </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setSelectedOrder(order)}
                          title="View order"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        {order.customer_email && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => navigate(`/admin/customer/${encodeURIComponent(order.customer_email)}`)}
                            title="Open Customer 360°"
                          >
                            <UserSearch className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Order Detail Dialog */}
      <Dialog open={!!selectedOrder} onOpenChange={() => setSelectedOrder(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Order Details</DialogTitle>
          </DialogHeader>

          {selectedOrder && (
            <div className="space-y-6">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <EntityTags entityType="order" entityId={selectedOrder.id} scope="order" />
                <EntityFollowers entityType="order" entityId={selectedOrder.id} compact />
              </div>
              {/* Order Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">Order ID</p>
                  <p className="font-mono text-sm">{selectedOrder.id}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Date</p>
                  <p>{format(new Date(selectedOrder.created_at), 'PPp')}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Customer</p>
                  <p className="font-medium">{selectedOrder.customer_name || 'Unknown'}</p>
                  <p className="text-sm text-muted-foreground">{selectedOrder.customer_email}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Status</p>
                  <Select
                    value={selectedOrder.status}
                    onValueChange={(status) => {
                      updateStatusMutation.mutate({ orderId: selectedOrder.id, status });
                      setSelectedOrder({ ...selectedOrder, status });
                    }}
                  >
                    <SelectTrigger className="w-40 mt-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="paid">Paid</SelectItem>
                      <SelectItem value="shipped">Shipped</SelectItem>
                      <SelectItem value="completed">Completed</SelectItem>
                      <SelectItem value="cancelled">Cancelled</SelectItem>
                      <SelectItem value="refunded">Refunded</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <Separator />

              {/* Fulfillment Progress */}
              <div>
                <h3 className="font-semibold mb-3">Fulfillment</h3>
                <FulfillmentStepper
                  status={(selectedOrder as any).fulfillment_status || 'unfulfilled'}
                  pickedAt={(selectedOrder as any).picked_at}
                  packedAt={(selectedOrder as any).packed_at}
                  shippedAt={(selectedOrder as any).shipped_at}
                  deliveredAt={(selectedOrder as any).delivered_at}
                />
                {(selectedOrder as any).tracking_number && (
                  <div className="mt-3 text-sm">
                    <span className="text-muted-foreground">Tracking: </span>
                    {(selectedOrder as any).tracking_url ? (
                      <a href={(selectedOrder as any).tracking_url} target="_blank" rel="noopener noreferrer" className="text-primary underline">
                        {(selectedOrder as any).tracking_number}
                      </a>
                    ) : (
                      <span className="font-mono">{(selectedOrder as any).tracking_number}</span>
                    )}
                  </div>
                )}
                <div className="mt-4">
                  <FulfillmentActions
                    orderId={selectedOrder.id}
                    currentStatus={(selectedOrder as any).fulfillment_status || 'unfulfilled'}
                    trackingNumber={(selectedOrder as any).tracking_number}
                    trackingUrl={(selectedOrder as any).tracking_url}
                    fulfillmentNotes={(selectedOrder as any).fulfillment_notes}
                    onUpdated={() => setSelectedOrder(null)}
                  />
                </div>
              </div>

              <Separator />

              {/* Order Items */}
              <div>
                <h3 className="font-semibold mb-3">Products</h3>
                <div className="space-y-2">
                  {orderItems?.map((item) => (
                    <div key={item.id} className="flex justify-between items-center py-2 border-b last:border-0">
                      <div>
                        <p className="font-medium">{item.product_name}</p>
                        <p className="text-sm text-muted-foreground">
                          {item.quantity} st × {formatPrice(item.price_cents, selectedOrder.currency)}
                        </p>
                      </div>
                      <p className="font-medium">
                        {formatPrice(item.price_cents * item.quantity, selectedOrder.currency)}
                      </p>
                    </div>
                  ))}
                </div>
              </div>

              <Separator />

              {/* Total */}
              <div className="flex justify-between items-center text-lg font-bold">
                <span>Total</span>
                <span>{formatPrice(selectedOrder.total_cents, selectedOrder.currency)}</span>
              </div>

              {/* Actions */}
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={() => sendConfirmationMutation.mutate(selectedOrder.id)}
                  disabled={sendConfirmationMutation.isPending}
                >
                  {sendConfirmationMutation.isPending ? (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Mail className="h-4 w-4 mr-2" />
                  )}
                  Send Order Confirmation
                </Button>
              </div>

              {/* Stripe Info */}
              {selectedOrder.stripe_checkout_id && (
                <div className="text-xs text-muted-foreground">
                  <p>Stripe Checkout: {selectedOrder.stripe_checkout_id}</p>
                  {selectedOrder.stripe_payment_intent && (
                    <p>Payment Intent: {selectedOrder.stripe_payment_intent}</p>
                  )}
                </div>
              )}

              <Separator />

              {/* Universal activity timeline */}
              <EntityActivityTimeline entityType="order" entityId={selectedOrder.id} title="Notes & Tasks" compact />
            </div>
          )}
        </DialogContent>
      </Dialog>
      </AdminPageContainer>
    </AdminLayout>
  );
}
