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';

export function OrdersPage() {
  const { instanceId } = useParams();
  const navigate = useNavigate();
  const [isCreating, setIsCreating] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  return (
    <>
      <OrdersView 
        refreshKey={refreshKey}
        onRowClick={(row) => {
          const id = row.instance_id as number | string | undefined;
          if (id != null) navigate(`/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(`/orders`)}
        title={instanceId != null ? `Order #${instanceId}` : undefined}
        width="lg"
      >
        {instanceId != null && <OrderDetail instanceId={instanceId} />}
      </Modal>
    </>
  );
}
