'use client';

import { useState } from 'react';

import { redirect, useRouter } from 'next/navigation';

import ConfirmationModal from '@/packages/shared/src/components/confirmation-modal';
import { StoreOrderLineItem } from '@medusajs/types';
import { formatDate } from 'date-fns';

import { pathsConfig } from '@kit/shared/config';
import { Button } from '@kit/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@kit/ui/table';
import { Trans } from '@kit/ui/trans';

import type { Order } from '~/lib/types/order';

import { cancelTtoBooking } from '../../_lib/server/actions';
import { logAnalysisResultsNavigateAction } from './actions';

export type OrderItemType = 'analysisOrder' | 'ttoService';

export default function OrderItemsTable({
  items,
  title,
  order,
  type = 'analysisOrder',
}: {
  items: StoreOrderLineItem[];
  title: string;
  order: Order;
  type?: OrderItemType;
}) {
  const router = useRouter();
  const [isConfirmOpen, setIsConfirmOpen] = useState(false);
  const isCancelOrderAllowed =
    order?.bookingCode &&
    order?.clinicId &&
    order?.medusaLineItemId &&
    order?.status === 'CONFIRMED';

  if (!items || items.length === 0) {
    return null;
  }

  const isAnalysisOrder = type === 'analysisOrder';
  const isTtoservice = type === 'ttoService';

  const openDetailedView = async () => {
    if (isAnalysisOrder && order?.medusaOrderId && order?.id) {
      await logAnalysisResultsNavigateAction(order.medusaOrderId);
      router.push(`${pathsConfig.app.analysisResults}/${order.id}`);
    } else {
      router.push(`${pathsConfig.app.myOrders}/${order.medusaOrderId}`);
    }
  };

  return (
    <Table className="border-separate rounded-lg border">
      <TableHeader className="text-ui-fg-subtle txt-medium-plus">
        <TableRow>
          <TableHead className="px-6">
            <Trans i18nKey={title} />
          </TableHead>
          <TableHead className="px-6">
            <Trans i18nKey="orders:table.createdAt" />
          </TableHead>
          {order.location && (
            <TableHead className="px-6">
              <Trans i18nKey="orders:table.location" />
            </TableHead>
          )}
          <TableHead className="px-6">
            <Trans i18nKey="orders:table.status" />
          </TableHead>
          {isAnalysisOrder && <TableHead className="px-6"></TableHead>}
        </TableRow>
      </TableHeader>
      <TableBody>
        {items
          .sort((a, b) =>
            (a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
          )
          .map((orderItem) => (
            <TableRow className="w-full" key={orderItem.id}>
              <TableCell className="w-[100%] px-6 text-left">
                <p className="txt-medium-plus text-ui-fg-base">
                  {orderItem.product_title}
                </p>
              </TableCell>

              <TableCell className="px-6 whitespace-nowrap">
                {formatDate(orderItem.created_at, 'dd.MM.yyyy HH:mm')}
              </TableCell>
              {order.location && (
                <TableCell className="min-w-[180px] px-6">
                  {order.location}
                </TableCell>
              )}
              <TableCell className="min-w-[180px] px-6">
                <Trans
                  i18nKey={`orders:status.${type}.${order?.status ?? 'CONFIRMED'}`}
                />
              </TableCell>

              <TableCell className="px-6 text-right">
                <Button size="sm" onClick={openDetailedView}>
                  <Trans i18nKey="analysis-results:view" />
                </Button>
                {isCancelOrderAllowed && (
                  <Button
                    size="sm"
                    className="bg-warning/90 hover:bg-warning mt-2 w-full"
                    onClick={() => setIsConfirmOpen(true)}
                  >
                    <Trans i18nKey="analysis-results:cancel" />
                  </Button>
                )}
              </TableCell>
            </TableRow>
          ))}
      </TableBody>
      {isCancelOrderAllowed && (
        <ConfirmationModal
          isOpen={isConfirmOpen}
          onClose={() => setIsConfirmOpen(false)}
          onConfirm={async () => {
            cancelTtoBooking(
              order.bookingCode!,
              order.clinicId!,
              order.medusaLineItemId!,
            ).then(() => {
              redirect(pathsConfig.app.myOrders);
            });
          }}
          titleKey="orders:confirmBookingCancel.title"
          descriptionKey="orders:confirmBookingCancel.description"
        />
      )}
    </Table>
  );
}
