import { useNavigate, useParams } from 'react-router-dom';
import { Modal } from '../components/reusable';
import { OrdersView } from '../components/rv';
import { OrderDetail } from '../components/dv';
import { useState } from 'react';
import { Button } from '../components/buttons/Button';
import { Plus } from 'lucide-react';
import { DynamicForm } from '../components/forms/DynamicForm';
import { ORDER_BOOKING } from '../api/config';
import { orderBookingClient } from '../api/clients';
import { useAuth } from '../auth/context';

export function MyOrdersPage() {
  const params = useParams();
  const instanceId = params.instanceId ? Number(params.instanceId) : undefined;
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  const { userEmail } = useAuth();

  return (
    <>
      <OrdersView 
        refreshKey={refreshKey}
        presetAlias="my_orders"
        initialFilters={userEmail ? { performed_by_email: userEmail } : undefined}
        onRowClick={(row) => {
          const id = row.instance_id as number | string | undefined;
          if (id != null) navigate(`/my-orders/${id}`);
        }} 
        headerActions={
          <Button size="sm" iconLeft={<Plus size={14} />} onClick={() => setIsCreating(true)}>
            Place Order
          </Button>
        }
      />

      <Modal
        open={isCreating}
        onClose={() => setIsCreating(false)}
        title="Place Order"
        width="md"
      >
        <DynamicForm 
          client={orderBookingClient} 
          activityId={ORDER_BOOKING.activities.LOG_VISIT.uid}
          onSuccess={() => {
            setIsCreating(false);
            setRefreshKey(k => k + 1);
          }}
          onCancel={() => setIsCreating(false)}
        />
      </Modal>

      <Modal
        open={instanceId != null}
        onClose={() => {
          navigate(`/my-orders`);
        }}
        title={instanceId != null ? `Order #${instanceId}` : undefined}
        width="lg"
      >
        {instanceId != null && <OrderDetail instanceId={instanceId} />}
      </Modal>
    </>
  );
}
