import React, { useEffect, useState } from "react";

import { TableBody, TableRow } from "@mui/material";
import Checkbox from "@mui/material/Checkbox";
import Input from "@mui/material/Input";

import Table from "../../../../components/Table";
import { TableCell } from "../../../../components/Table/TableCell";
import TableHead from "../../../../components/Table/TableHead";
import TableHeading from "../../../../components/Table/TableHeading";
import { useCardContext } from "../../../../contexts/CardContext";
import { useI18n } from "../../../../contexts/I18nContext";
import { OrderItem } from "../../types/order";

export interface ShipmentItemsTableProps {
  items: OrderItem[];
  isPending: boolean;
  onSelect?: (selected: OrderItem[]) => void;
}

export const OrderItemsTable: React.FC<ShipmentItemsTableProps> = ({
  items,
  isPending,
  onSelect,
}) => {
  const { t } = useI18n();
  const [selected, setSelected] = useState<OrderItem[]>([]);
  const { isEditing } = useCardContext();

  const toggleSelectAll = (_: React.ChangeEvent<HTMLInputElement>, checked: boolean) => {
    setSelected(checked ? items : []);
  };

  const toggleItem = (item: OrderItem, checked: boolean) => {
    const index = selected.map(({ code }) => code).indexOf(item.code);

    if (checked && index === -1) {
      setSelected([...selected, item]);
    } else {
      const unselected = [...selected];
      unselected.splice(index, 1);
      setSelected(unselected);
    }
  };

  const itemQuantityChange = (item: OrderItem) => {
    const index = selected.map(({ code }) => code).indexOf(item.code);
    const changed = [...selected];
    changed[index] = item;
    setSelected(changed);
  };

  useEffect(() => {
    if (onSelect != null) onSelect(selected);
  }, [onSelect, selected]);

  return (
    <Table count={items.length}>
      <TableHead>
        {isEditing && isPending && (
          <TableHeading align="left" padding="checkbox">
            <Checkbox
              checked={items.length !== 0 && selected.length === items.length}
              color="secondary"
              disabled={items.length === 0}
              indeterminate={selected.length > 0 && selected.length < items.length}
              onChange={toggleSelectAll}
            />
          </TableHeading>
        )}
        <TableHeading align="left">{t("Item")}</TableHeading>
        <TableHeading align="left">{t("SKU")}</TableHeading>
        <TableHeading align="right">{t("Quantity")}</TableHeading>
      </TableHead>

      <TableBody>
        {items.map((item) => {
          const isSelected = selected.map(({ code }) => code).includes(item.code);
          return (
            <TableRow key={item.code}>
              {isEditing && isPending ? (
                <TableCell align="left" padding="checkbox">
                  <Checkbox
                    checked={isSelected}
                    color="secondary"
                    onChange={(_, checked) => toggleItem(item, checked)}
                  />
                </TableCell>
              ) : null}
              <TableCell align="left">{item.name}</TableCell>
              <TableCell align="left">{item.code}</TableCell>
              <TableCell align="right">
                {isEditing && isPending ? (
                  <Input
                    color="secondary"
                    defaultValue={item.quantity}
                    disabled={!isSelected}
                    inputProps={{ min: 0, max: item.quantity }}
                    type="number"
                    onChange={(event) =>
                      itemQuantityChange({
                        ...item,
                        quantity: Number.parseInt(event.target.value),
                      })
                    }
                  />
                ) : (
                  item.quantity
                )}
              </TableCell>
            </TableRow>
          );
        })}
      </TableBody>
    </Table>
  );
};

export default OrderItemsTable;
