import { updateTripState } from '@/services/controller/TripController';
import { useIntl, useModel } from '@umijs/max';
import { Button, message, Popconfirm } from 'antd';
import React from 'react';
import CancelTrip from './CancelTrip';

interface TripCancleOrFinishedButtonProps {
  tripStatus?: number;
  onCallBack?: (success: boolean) => void;
}

const TripCancleOrFinishedButton: React.FC<TripCancleOrFinishedButtonProps> = ({
  tripStatus,
  onCallBack,
}) => {
  const { getApi } = useModel('getTrip');
  const intl = useIntl();
  const handleClickButton = async (state: number, note?: string) => {
    try {
      await updateTripState({ status: state, note: note || '' });
      message.success(
        intl.formatMessage({ id: 'trip.finishButton.updateSuccess' }),
      );
      getApi();
      onCallBack?.(true);
    } catch (error) {
      console.error('Error updating trip status:', error);
      message.error(
        intl.formatMessage({ id: 'trip.finishButton.updateError' }),
      );
      onCallBack?.(false);
    }
  };
  const renderButton = () => {
    switch (tripStatus) {
      case 3: // Đang hoạt động
        return (
          <div className="flex gap-3">
            <CancelTrip
              onFinished={async (note) => {
                await handleClickButton(5, note);
              }}
            />
            <Popconfirm
              title={intl.formatMessage({
                id: 'trip.finishButton.confirmTitle',
              })}
              description={intl.formatMessage({
                id: 'trip.finishButton.confirmMessage',
              })}
              onConfirm={async () => handleClickButton(4)}
              okText={intl.formatMessage({
                id: 'trip.finishButton.confirmYes',
              })}
              cancelText={intl.formatMessage({
                id: 'trip.finishButton.confirmNo',
              })}
            >
              <Button color="orange" variant="solid">
                {intl.formatMessage({ id: 'trip.finishButton.end' })}
              </Button>
            </Popconfirm>
          </div>
        );
      default:
        return null;
    }
  };

  return <div>{renderButton()}</div>;
};

export default TripCancleOrFinishedButton;
