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 { MasterProps } from '../MasterItem/MasterItem';
import { getTimeSlot } from '../../lib';
import { armService } from '../../api/arm';

const statuses = [
  'pending' as const,
  'progress' as const,
  'working' as const,
  'canceled' as const,
  'complete' as const,
];

type GetArrItemType<ArrType> =
  ArrType extends Array<infer ItemType> ? ItemType : never;

export type OrderProps = {
  carNumber?: string;
  startWashTime?: string;
  endWashTime?: string;
  orderDate?: string;
  status?: GetArrItemType<typeof statuses>;
  phone?: string;
  location?: string;
  master: MasterProps;
  notes: '';
  allMasters: MasterProps[];
  id: string;
};

type Status = (typeof statuses)[number];

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,
}: OrderProps) => {
  const { updateOrders } = armService();

  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, masterId: selectedMaster.id });
    } else {
      console.error('Master not found');
    }
  };

  const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
    const status = e.target.value;
    updateOrders({ id, status });
    setStatus(e.target.value as OrderProps['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;
