'use client';

import { useState, useEffect } from 'react';
import { toast } from 'react-hot-toast';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../src/components/ui/table";
import { createPortal } from 'react-dom';
import { Button } from '../../../../../src/components/ui/button';
import { Edit, Eye, X, Search, Trash2, ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
import { Tooltip } from '../../../../../src/components/ui/tooltip';
import { Badge } from '../../../../../src/components/ui/badge';
import { Label } from '@radix-ui/react-label';
import { Input } from '../../../../../src/components/ui/input';

interface Order {
  _id: string;
  order_id: string | null;
  customer_name: string;
  customer_phone: string;
  customer_email: string;
  total_amount: number;
  order_status: string;
  device: string;
  createdAt: string;
  payment_method?: string;
  payment_status?: string;
  shipping_charge?: number;
  discount?: number;
  order_placed_at?: string;
  updatedAt?: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  pages: number;
}

const OrderManagement = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [sortField, setSortField] = useState<"createdAt" | "total_amount" | "customer_name" | "order_id">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [viewingOrder, setViewingOrder] = useState<Order | null>(null);
  const [viewModal, setViewModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);

  // Form states
  const [formData, setFormData] = useState({
    _id: null,
    customer_name: '',
    customer_phone: '',
    customer_email: '',
    total_amount: '',
    device: 'website',
    order_status: ''
  });

  // Fetch orders
  const fetchOrders = async (page = 1, search = '', status = 'all', sort = sortField, order = sortOrder) => {
    try {
      setLoading(true);

      const params = new URLSearchParams({
        page: page.toString(),
        limit: '10',
        sort: sort,
        order: order,
        ...(search && { search }),
        ...(status !== 'all' && { status })
      });

      const res = await fetch(`/api/orders?${params}`);
      const data = await res.json();

      if (data.success) {
        setOrders(data.data);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || 'Failed to fetch orders');
      }
    } catch {
      toast.error('Failed to fetch orders');
    } finally {
      setLoading(false);
    }
  };

  const handleSort = (field: "createdAt" | "total_amount" | "customer_name" | "order_id") => {
    const newOrder = sortField === field && sortOrder === "asc" ? "desc" : "asc";
    setSortField(field);
    setSortOrder(newOrder);
    fetchOrders(pagination.page, searchTerm, statusFilter, field, newOrder);
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  useEffect(() => {
    const t = setTimeout(() => {
      fetchOrders(1, searchTerm, statusFilter, sortField, sortOrder);
    }, 500);
    return () => clearTimeout(t);
  }, [searchTerm, statusFilter, sortField, sortOrder]);

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchOrders(page, searchTerm, statusFilter, sortField, sortOrder);
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      _id: null,
      customer_name: '',
      customer_phone: '',
      customer_email: '',
      total_amount: '',
      device: 'website',
      order_status: ''
    });
  };

  // Handle create order
  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.customer_name || !formData.customer_email || !formData.total_amount) {
      toast.error('All required fields must be filled');
      return;
    }

    try {
      setSubmitting(true);

      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          total_amount: Number(formData.total_amount)
        })
      });

      const data = await res.json();

      if (data.success) {
        toast.success('Order created successfully');
        setShowCreateModal(false);
        resetForm();
        fetchOrders(pagination.page, searchTerm, statusFilter, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to create order');
      }
    } catch {
      toast.error('Failed to create order');
    } finally {
      setSubmitting(false);
    }
  };

  // Handle edit order (for status change)
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData?._id) return;

    try {
      setSubmitting(true);

      const { _id, ...rest } = formData;
      const response = await fetch(`/api/orders/${formData._id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(rest)
      });

      const data = await response.json();

      if (data.success) {
        toast.success('Order updated successfully');
        setShowEditModal(false);
        resetForm();
        fetchOrders(pagination.page, searchTerm, statusFilter, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to update order');
      }
    } catch (error) {
      console.error('Error updating order:', error);
      toast.error('Failed to update order');
    } finally {
      setSubmitting(false);
    }
  };

  // Handle status change directly from table
  const handleStatusChange = async (orderId: string, newStatus: string) => {
    try {
      setSubmitting(true);
      
      const response = await fetch(`/api/orders/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ order_status: newStatus })
      });

      const data = await response.json();

      if (data.success) {
        toast.success(`Order status updated to ${newStatus}`);
        fetchOrders(pagination.page, searchTerm, statusFilter, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch (error) {
      console.error('Error updating status:', error);
      toast.error('Failed to update status');
    } finally {
      setSubmitting(false);
    }
  };

  // Handle delete order
  const handleDelete = async () => {
    if (!selectedOrder) return;

    try {
      setSubmitting(true);

      const res = await fetch(`/api/orders/${selectedOrder._id}`, {
        method: 'DELETE'
      });

      const data = await res.json();

      if (data.success) {
        toast.success('Order deleted successfully');
        setShowDeleteModal(false);
        setSelectedOrder(null);
        fetchOrders(pagination.page, searchTerm, statusFilter, sortField, sortOrder);
      } else {
        toast.error(data.error || 'Failed to delete order');
      }
    } catch {
      toast.error('Failed to delete order');
    } finally {
      setSubmitting(false);
    }
  };

  const handleClickEdit = (data: any) => {
    setFormData({
      _id: data?._id,
      customer_name: data?.customer_name,
      customer_phone: data?.customer_phone,
      customer_email: data?.customer_email,
      total_amount: data?.total_amount,
      device: data?.device,
      order_status: data?.order_status
    });
    setShowEditModal(true);
  };

  const handleClickView = (data: any) => {
    setViewingOrder(data);
    setViewModal(true);
  };

  // Open delete modal
  const openDeleteModal = (order: Order) => {
    setSelectedOrder(order);
    setShowDeleteModal(true);
  };

  // Close modal
  const handleCloseModal = () => {
    setShowCreateModal(false);
    setShowEditModal(false);
    resetForm();
  };

  // Status badge color
  const getStatusStyle = (status: string) => {
    switch (status.toLowerCase()) {
      case 'delivered':
        return 'bg-green-100 text-green-800';
      case 'cancelled':
        return 'bg-red-100 text-red-800';
      case 'shipped':
        return 'bg-purple-100 text-purple-800';
      case 'processing':
        return 'bg-blue-100 text-blue-800';
      default:
        return 'bg-yellow-100 text-yellow-800';
    }
  };

  const formatDate = (dateString: string | undefined) => {
    if (!dateString) return;
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // Status options for dropdown
  const statusOptions = [
    { value: 'pending', label: 'Pending' },
    { value: 'processing', label: 'Processing' },
    { value: 'shipped', label: 'Shipped' },
    { value: 'delivered', label: 'Delivered' },
    { value: 'cancelled', label: 'Cancelled' }
  ];

  return (
    <div className="p-0">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <Dialog open={showCreateModal || showEditModal} onOpenChange={handleCloseModal}>
          <DialogContent className="max-w-2xl">
            <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
              <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                <DialogHeader>
                  <DialogTitle>{showEditModal ? 'Edit Order' : 'Add New Order'}</DialogTitle>
                </DialogHeader>
                <form onSubmit={showCreateModal ? handleCreate : handleEdit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                    <div className="mb-4">
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Customer Name *
                      </label>
                      <input
                        type="text"
                        value={formData.customer_name}
                        onChange={(e) => setFormData({ ...formData, customer_name: e.target.value })}
                        className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        required
                      />
                    </div>

                    <div className="mb-4">
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Phone
                      </label>
                      <input
                        type="text"
                        value={formData.customer_phone}
                        onChange={(e) => setFormData({ ...formData, customer_phone: e.target.value })}
                        className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                      />
                    </div>

                    <div className="mb-4">
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Email *
                      </label>
                      <input
                        type="email"
                        value={formData.customer_email}
                        onChange={(e) => setFormData({ ...formData, customer_email: e.target.value })}
                        className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        required
                      />
                    </div>

                    <div className="mb-4">
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Total Amount *
                      </label>
                      <input
                        type="number"
                        value={formData.total_amount}
                        onChange={(e) => setFormData({ ...formData, total_amount: e.target.value })}
                        className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        required
                      />
                    </div>

                    {showEditModal && (
                      <div className="mb-4">
                        <label className="mb-2.5 block font-medium text-black dark:text-white">
                          Order Status
                        </label>
                        <select
                          value={formData.order_status}
                          onChange={(e) => setFormData({ ...formData, order_status: e.target.value })}
                          className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        >
                          {statusOptions.map(option => (
                            <option key={option.value} value={option.value}>
                              {option.label}
                            </option>
                          ))}
                        </select>
                      </div>
                    )}

                    <div className="mb-6">
                      <label className="mb-2.5 block font-medium text-black dark:text-white">
                        Device
                      </label>
                      <select
                        value={formData.device}
                        onChange={(e) => setFormData({ ...formData, device: e.target.value })}
                        className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                      >
                        <option className="text-black bg-white" value="website">Website</option>
                        <option className="text-black bg-white" value="mobile">Mobile</option>
                      </select>
                    </div>
                  </div>

                  <div className="flex justify-end space-x-3 p-4 pb-0">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleCloseModal}
                    >
                      Cancel
                    </Button>
                    <button
                      type="submit"
                      disabled={submitting}
                      className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {showEditModal ? (submitting ? 'Updating...' : 'Update Order')
                        : (submitting ? 'Creating...' : 'Create Order')}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            type="text"
            placeholder="Search orders..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className='pl-10'
          />
          <X
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
            onClick={() => setSearchTerm('')}
          />
        </div>

        <div className="sm:w-48">
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="w-full rounded-lg border-[1.5px] border-stroke bg-transparent px-5 py-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
          >
            <option className="text-black bg-white" value="all">All Status</option>
            <option className="text-black bg-white" value="pending">Pending</option>
            <option className="text-black bg-white" value="processing">Processing</option>
            <option className="text-black bg-white" value="shipped">Shipped</option>
            <option className="text-black bg-white" value="delivered">Delivered</option>
            <option className="text-black bg-white" value="cancelled">Cancelled</option>
          </select>
        </div>
      </div>

      {/* Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader className="dark:bg-gray-800">
            <TableRow>
              <TableHead 
                className="cursor-pointer hover:bg-gray-50"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc" ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-gray-50 "
                onClick={() => handleSort("order_id")}
              >
                <div className="flex   gap-2">
                  Order ID
                  {sortField === "order_id" ? (
                    sortOrder === "asc" ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-gray-50"
                onClick={() => handleSort("customer_name")}
              >
                <div className="flex items-center gap-2">
                  Customer
                  {sortField === "customer_name" ? (
                    sortOrder === "asc" ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-gray-50"
                onClick={() => handleSort("total_amount")}
              >
                <div className="flex items-center gap-2">
                  Total
                  {sortField === "total_amount" ? (
                    sortOrder === "asc" ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead>Status</TableHead>
              {/* <TableHead>Device</TableHead> */}
              <TableHead>Created</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className='dark:bg-[#1f2a37]'>
            {loading ? (
              <TableRow>
                <TableCell colSpan={7} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                    <span className="ml-2">Loading...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : orders.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="px-4 py-8 text-center text-gray-500">
                  No orders found
                </TableCell>
              </TableRow>
            ) : (
              orders.map((order, index) => (
                <TableRow key={order._id}>
                  <TableCell className="text-center">
                    {((pagination?.page - 1) * pagination?.limit) + index + 1}
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 pl-9 dark:border-strokedark xl:pl-11">
                    <p className="text-sm font-medium test-left text-black dark:text-white">
                      {order.order_id}
                    </p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-sm font-medium text-black dark:text-white">
                      {order.customer_name}
                    </p>
                    <p className="text-xs text-gray-500">{order.customer_email}</p>
                    {order.customer_phone && (
                      <p className="text-xs text-gray-500">{order.customer_phone}</p>
                    )}
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">₹{order.total_amount}</p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <select
                      value={order.order_status}
                      onChange={(e) => handleStatusChange(order._id, e.target.value)}
                      className={`inline-flex rounded-full px-3 py-1 text-sm font-medium border-0 focus:ring-2 focus:ring-primary ${getStatusStyle(order.order_status)}`}
                      disabled={submitting}
                    >
                      {statusOptions.map(option => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                  </TableCell>
                  {/* <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white capitalize">{order.device}</p>
                  </TableCell> */}
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <p className="text-black dark:text-white">
                      {new Date(order.createdAt).toLocaleDateString()}
                    </p>
                  </TableCell>
                  <TableCell className="border-b border-[#eee] px-4 py-5 dark:border-strokedark">
                    <div className="flex items-center space-x-3.5">
                      <Tooltip text='View'>
                        <Button size="sm" variant="outline" onClick={() => handleClickView(order)}>
                          <Eye className='w-4 h-4' />
                        </Button>
                      </Tooltip>
                      {/* <Tooltip text='Edit'>
                        <Button size="sm" variant="outline" onClick={() => handleClickEdit(order)}>
                          <Edit className='w-4 h-4' />
                        </Button>
                      </Tooltip> */}
                      <Tooltip text='Delete'>
                        <Button
                          onClick={() => openDeleteModal(order)}
                          size='sm'
                          variant='outline'
                        >
                          <Trash2 className='w-4 h-4' />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="mt-4 flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Showing {((pagination.page - 1) * pagination.limit) + 1} to{' '}
            {Math.min(pagination.page * pagination.limit, pagination.total)} of{' '}
            {pagination.total} entries
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => handlePageChange(pagination.page - 1)}
              disabled={pagination.page === 1}
              className="rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-strokedark dark:text-white"
            >
              Previous
            </button>
            {Array.from({ length: pagination.pages }, (_, i) => i + 1).map((page) => (
              <button
                key={page}
                onClick={() => handlePageChange(page)}
                className={`rounded-lg border px-3 py-2 text-sm font-medium ${page === pagination.page
                  ? 'border-primary bg-primary text-white'
                  : 'border-stroke text-black hover:bg-gray-50 dark:border-strokedark dark:text-white'
                }`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => handlePageChange(pagination.page + 1)}
              disabled={pagination.page === pagination.pages}
              className="rounded-lg border border-stroke px-3 py-2 text-sm font-medium text-black hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-strokedark dark:text-white"
            >
              Next
            </button>
          </div>
        </div>
      )}

      {/* View order */}
      <Dialog open={viewModal} onOpenChange={setViewModal}>
        <DialogContent className="max-w-2xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader className="flex-shrink-0">
                <DialogTitle>Order Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setViewModal(false);
                  }}
                />
              </DialogHeader>

              {viewingOrder && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                    <div className="space-y-5 pb-4">

                      {/* Order ID + Status */}
                      <div className="flex items-center justify-between p-3 bg-muted/40 rounded-lg border">
                        <div>
                          <p className="text-xs text-muted-foreground">Order ID</p>
                          <p className="text-sm font-mono font-medium">{viewingOrder.order_id}</p>
                        </div>
                        <Badge variant={
                          viewingOrder.order_status === 'delivered' ? 'default' :
                            viewingOrder.order_status === 'cancelled' ? 'destructive' : 'secondary'
                        }>
                          {viewingOrder.order_status}
                        </Badge>
                      </div>

                      {/* Customer Info */}
                      <div>
                        <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">Customer</p>
                        <div className="grid grid-cols-2 gap-3">
                          <div className="space-y-0.5">
                            <Label className="text-sm text-muted-foreground">Name</Label>
                            <p className="text-sm font-medium">{viewingOrder.customer_name}</p>
                          </div>
                          <div className="space-y-0.5">
                            <Label className="text-sm text-muted-foreground">Phone</Label>
                            <p className="text-sm">{viewingOrder.customer_phone || '—'}</p>
                          </div>
                          <div className="col-span-2 space-y-0.5">
                            <Label className="text-sm text-muted-foreground">Email</Label>
                            <p className="text-sm">{viewingOrder.customer_email}</p>
                          </div>
                        </div>
                      </div>

                      <div className="border-t" />

                      {/* Payment Info */}
                      <div>
                        <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">Payment</p>
                        <div className="grid grid-cols-2 gap-3">
                          <div className="space-y-0.5">
                            <Label className="text-xs text-muted-foreground">Payment Method</Label>
                            <p className="text-sm uppercase">{viewingOrder.payment_method || '—'}</p>
                          </div>
                          <div className="space-y-0.5">
                            <Label className="text-xs text-muted-foreground">Payment Status</Label>
                            <Badge variant={viewingOrder.payment_status === 'paid' ? 'default' : 'secondary'}>
                              {viewingOrder.payment_status || '—'}
                            </Badge>
                          </div>
                        </div>
                      </div>

                      <div className="border-t" />

                      {/* Amount Breakdown */}
                      <div>
                        <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">Amount</p>
                        <div className="space-y-2 bg-muted/40 rounded-lg p-3">
                        <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Purchase Amount</span>
                            <span>₹{viewingOrder.total_amount?.toLocaleString() || 0}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Shipping Charge</span>
                            <span>₹{viewingOrder.shipping_charge?.toLocaleString() || 0}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Discount</span>
                            <span className="text-green-600">- ₹{viewingOrder.discount?.toLocaleString() || 0}</span>
                          </div>
                          <div className="border-t pt-2 flex justify-between text-sm font-semibold">
                            <span>Total Amount</span>
                            <span>
                              ₹
                              {(
                                (Number(viewingOrder.total_amount) || 0) -
                                (Number(viewingOrder.discount) || 0) +
                                (Number(viewingOrder.shipping_charge) || 0)
                              ).toLocaleString()}
                            </span>                          
                            </div>
                        </div>
                      </div>

                      <div className="border-t" />

                      {/* Meta Info */}
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-0.5">
                          <Label className="text-xs text-muted-foreground">Device</Label>
                          <p className="text-sm capitalize">{viewingOrder.device}</p>
                        </div>
                        <div className="space-y-0.5">
                          <Label className="text-xs text-muted-foreground">Order Placed At</Label>
                          <p className="text-xs">{formatDate(viewingOrder?.order_placed_at)}</p>
                        </div>
                        <div className="space-y-0.5">
                          <Label className="text-xs text-muted-foreground">Created At</Label>
                          <p className="text-xs">{formatDate(viewingOrder.createdAt)}</p>
                        </div>
                        <div className="space-y-0.5">
                          <Label className="text-xs text-muted-foreground">Last Updated</Label>
                          <p className="text-xs">{formatDate(viewingOrder?.updatedAt)}</p>
                        </div>
                      </div>

                    </div>
                  </div>

                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => {
                        setViewModal(false);
                        openDeleteModal(viewingOrder);
                      }}
                    >
                      <Trash2 className="w-4 h-4" />
                      Delete
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Delete Modal */}
      {showDeleteModal && selectedOrder && createPortal(
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50">
          <div className="z-[10000] w-full max-w-md rounded-lg bg-white p-6 dark:bg-boxdark">
            <div className="mb-4">
              <h3 className="text-lg font-semibold text-gray-600 dark:text-black">
                Delete Order
              </h3>
            </div>

            <p className="mb-6 text-sm text-gray-600 dark:text-black">
              Are you sure you want to delete order "{selectedOrder.order_id}" for{' '}
              {selectedOrder.customer_name}? This action cannot be undone.
            </p>

            <div className="flex justify-end space-x-3">
              <Button
                type="button"
                variant="outline"
                className='text-black'
                onClick={() => {
                  setShowDeleteModal(false);
                  setSelectedOrder(null);
                }}
              >
                Cancel
              </Button>
              <button
                onClick={handleDelete}
                disabled={submitting}
                className="rounded-lg bg-red-500 px-6 py-2 text-sm font-medium text-white hover:bg-red-600 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {submitting ? 'Deleting...' : 'Delete Order'}
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
};

export default OrderManagement;