import React, { ChangeEvent, useState } from 'react';
import { Td, Tr, Link, Select } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';

import { getTimeSlot } from '../../lib';
import { useUpdateOrdersMutation } from '../../__data__/service/api';
import { OrderArm, Status, statuses } from '../../models/api';

const statusColors: Record<Status, string> = {
  pending: 'yellow.100',
  progress: 'blue.100',
  working: 'orange.100',
  canceled: 'red.100',
  complete: 'green.100',
};

const OrderItem = ({
  carNumber,
  startWashTime,
  endWashTime,
  orderDate,
  status,
  phone,
  location,
  master,
  allMasters,
  id,
}: OrderArm) => {
  const [updateOrders] = useUpdateOrdersMutation();
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.arm.order',
  });

  const [statusSelect, setStatus] = useState(status);
  const bgColor = statusColors[statusSelect];
  const [masterSelect, setMaster] = useState(master?.name);

  const handelChangeMasters = (e: ChangeEvent<HTMLSelectElement>) => {
    const masterName = e.target.value;
    const selectedMaster = allMasters.find(
      (master) => master.name === masterName,
    );

    if (selectedMaster) {
      setMaster(masterName);
      updateOrders({ id, master: selectedMaster.id });
    } else {
      console.error('Master not found');
    }
  };

  const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
    const status = e.target.value as OrderArm['status'];
    updateOrders({ id, status });
    setStatus(status);
  };

  return (
    <Tr>
      <Td>{carNumber}</Td>
      <Td>
        {dayjs(orderDate).format('DD.MM.YYYY')} <br />
        {getTimeSlot(startWashTime, endWashTime)}
      </Td>
      <Td>
        <Select
          value={statusSelect}
          onChange={handeChangeStatus}
          placeholder={t(`status.placeholder`)}
          bg={bgColor}
        >
          {statuses.map((status) => (
            <option key={status} value={status}>
              {t(`status.${status}`)}
            </option>
          ))}
        </Select>
      </Td>
      <Td>
        <Select
          value={masterSelect}
          onChange={handelChangeMasters}
          placeholder={t(`master.placeholder`)}
        >
          {allMasters.map((item) => (
            <option key={item.id} value={item.name}>
              {item.name}
            </option>
          ))}
        </Select>
      </Td>
      <Td>
        <Link href='tel:'>{phone}</Link>
      </Td>
      <Td>{location}</Td>
    </Tr>
  );
};

export default OrderItem;
