import { STATUS } from '@/constants/enums';
import { getGPS } from '@/services/controller/DeviceController';
import {
  startNewHaul,
  updateTripState,
} from '@/services/controller/TripController';
import { PlusOutlined } from '@ant-design/icons';
import { useIntl, useModel } from '@umijs/max';
import { Button, Grid, message } from 'antd';
import { useState } from 'react';
import CreateOrUpdateFishingLog from './CreateOrUpdateFishingLog';

interface CreateNewHaulOrTripProps {
  trips?: API.Trip;
  onCallBack?: (success: string) => void;
}

const CreateNewHaulOrTrip: React.FC<CreateNewHaulOrTripProps> = ({
  trips,
  onCallBack,
}) => {
  const [isFinishHaulModalOpen, setIsFinishHaulModalOpen] = useState(false);
  const intl = useIntl();
  const { getApi } = useModel('getTrip');
  const checkHaulFinished = () => {
    return trips?.fishing_logs?.some((h) => h.status === 0);
  };
  const { useBreakpoint } = Grid;
  const screens = useBreakpoint();

  const createNewHaul = async () => {
    if (trips?.fishing_logs?.some((f) => f.status === 0)) {
      message.warning(
        intl.formatMessage({ id: 'trip.warning.haulNotFinished' }),
      );
      return;
    }

    try {
      const gpsData = await getGPS();
      // console.log('GPS Data:', gpsData);

      const body: API.NewFishingLogRequest = {
        trip_id: trips?.id || '',
        start_at: new Date(),
        start_lat: gpsData.lat,
        start_lon: gpsData.lon,
        weather_description: intl.formatMessage({ id: 'trip.weather' }),
      };

      await startNewHaul(body);
      onCallBack?.(STATUS.CREATE_FISHING_LOG_SUCCESS);
      getApi();
    } catch (error) {
      console.log(error);
      onCallBack?.(STATUS.CREATE_FISHING_LOG_FAIL);
    }
  };

  const handleStartTrip = async (state: number, note?: string) => {
    if (trips?.trip_status !== 2) {
      message.warning(intl.formatMessage({ id: 'trip.warning.tripStarted' }));
      return;
    }
    try {
      await updateTripState({ status: state, note: note || '' });
      onCallBack?.(STATUS.START_TRIP_SUCCESS);
      getApi();
    } catch (error) {
      console.error('Error stating trip :', error);
      onCallBack?.(STATUS.START_TRIP_FAIL);
    }
  };

  // Không render gì nếu trip đã hoàn thành hoặc bị hủy
  if (trips?.trip_status === 4 || trips?.trip_status === 5) {
    return null;
  }

  return (
    <div
      style={{
        padding: screens.sm ? '0px' : '10px',
        marginRight: screens.sm ? '24px' : '0px',
      }}
    >
      {trips?.trip_status === 2 ? (
        <Button
          color="green"
          variant="solid"
          onClick={async () => handleStartTrip(3)}
        >
          {intl.formatMessage({ id: 'trip.startTrip' })}
        </Button>
      ) : checkHaulFinished() ? (
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={async () => {
            setIsFinishHaulModalOpen(true);
          }}
          color="geekblue"
          variant="solid"
        >
          {intl.formatMessage({ id: 'trip.finishHaul' })}
        </Button>
      ) : (
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={async () => {
            createNewHaul();
          }}
          color="cyan"
          variant="solid"
        >
          {intl.formatMessage({ id: 'trip.startHaul' })}
        </Button>
      )}

      <CreateOrUpdateFishingLog
        trip={trips!}
        isFinished={false}
        fishingLogs={undefined}
        isOpen={isFinishHaulModalOpen}
        onOpenChange={setIsFinishHaulModalOpen}
        onFinished={(success) => {
          if (success) {
            onCallBack?.(STATUS.UPDATE_FISHING_LOG_SUCCESS);
            getApi();
          } else {
            onCallBack?.(STATUS.UPDATE_FISHING_LOG_FAIL);
          }
        }}
      />
    </div>
  );
};

export default CreateNewHaulOrTrip;
