import { DeleteButton, EditButton } from '@/components/shared/Button';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { FormattedMessage, useIntl, useModel } from '@umijs/max';
import { DatePicker, Divider } from 'antd';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { useRef, useState } from 'react';
import CreateTrip from './components/CreateTrip';
import EditTrip from './components/EditTrip';
import TripCrews from './components/TripCrews';

import { DATE_TIME_FORMAT, DEFAULT_PAGE_SIZE } from '@/constants';
import { apiQueryTrips } from '@/services/slave/sgw/TripController';

dayjs.extend(utc);
dayjs.extend(timezone);

const TripList: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const { currentUserProfile } = initialState || {};

  // State bổ sung cho các biến bị thiếu
  const [currentRow, setCurrentRow] = useState<SgwModel.Trip>();
  const [editOpen, setEditOpen] = useState(false);

  const columns: ProColumns<SgwModel.Trip>[] = [
    {
      title: intl.formatMessage({
        id: 'pages.trips.name',
        defaultMessage: 'Tên chuyến đi',
      }),
      dataIndex: 'name',
      key: 'name',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'pages.trips.ship_id',
        defaultMessage: 'Mã tàu',
      }),
      dataIndex: 'ship_id',
      key: 'ship_id',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'pages.trips.departure_time',
        defaultMessage: 'Ngày đi',
      }),
      dataIndex: 'departure_time',
      key: 'departure_time',
      valueType: 'dateRange',
      render: (_, record) => {
        return record.departure_time
          ? dayjs(record.departure_time).format(DATE_TIME_FORMAT)
          : '-';
      },
      renderFormItem: (_, config, form) => {
        return (
          <DatePicker.RangePicker
            width="50%"
            presets={[
              {
                label: intl.formatMessage({
                  id: 'pages.date.yesterday',
                  defaultMessage: 'Yesterday',
                }),
                value: [dayjs().add(-1, 'd'), dayjs()],
              },
              {
                label: intl.formatMessage({
                  id: 'pages.date.lastweek',
                  defaultMessage: 'Last Week',
                }),
                value: [dayjs().add(-7, 'd'), dayjs()],
              },
              {
                label: intl.formatMessage({
                  id: 'pages.date.lastmonth',
                  defaultMessage: 'Last Month',
                }),
                value: [dayjs().add(-30, 'd'), dayjs()],
              },
            ]}
            onChange={(dates) => {
              form.setFieldsValue({ departure_time: dates });
            }}
          />
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'pages.trips.arrival_time',
        defaultMessage: 'Ngày về',
      }),
      dataIndex: 'arrival_time',
      key: 'arrival_time',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => {
        return record.arrival_time
          ? dayjs(record.arrival_time).format(DATE_TIME_FORMAT)
          : '-';
      },
      renderFormItem: (_, config, form) => {
        return (
          <DatePicker.RangePicker
            width="50%"
            presets={[
              {
                label: intl.formatMessage({
                  id: 'pages.date.yesterday',
                  defaultMessage: 'Yesterday',
                }),
                value: [dayjs().add(-1, 'd'), dayjs()],
              },
              {
                label: intl.formatMessage({
                  id: 'pages.date.lastweek',
                  defaultMessage: 'Last Week',
                }),
                value: [dayjs().add(-7, 'd'), dayjs()],
              },
              {
                label: intl.formatMessage({
                  id: 'pages.date.lastmonth',
                  defaultMessage: 'Last Month',
                }),
                value: [dayjs().add(-30, 'd'), dayjs()],
              },
            ]}
            onChange={(dates) => {
              form.setFieldsValue({ arrival_time: dates });
            }}
          />
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'pages.trips.status',
        defaultMessage: 'Trạng thái',
      }),
      dataIndex: 'trip_status',
      key: 'trip_status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: intl.formatMessage({
            id: 'pages.trips.status.created',
            defaultMessage: 'Đã khởi tạo',
          }),
          status: 'Default',
        },
        1: {
          text: intl.formatMessage({
            id: 'pages.trips.status.pending_approval',
            defaultMessage: 'Chờ duyệt',
          }),
          status: 'Processing',
        },
        2: {
          text: intl.formatMessage({
            id: 'pages.trips.status.approved',
            defaultMessage: 'Đã duyệt',
          }),
          status: 'Success',
        },
        3: {
          text: intl.formatMessage({
            id: 'pages.trips.status.active',
            defaultMessage: 'Đang hoạt động',
          }),
          status: 'Success',
        },
        4: {
          text: intl.formatMessage({
            id: 'pages.trips.status.completed',
            defaultMessage: 'Hoàn thành',
          }),
          status: 'Success',
        },
        5: {
          text: intl.formatMessage({
            id: 'pages.trips.status.cancelled',
            defaultMessage: 'Đã huỷ',
          }),
          status: 'Error',
        },
      },
    },
    {
      title: (
        <FormattedMessage id="pages.things.option" defaultMessage="Operating" />
      ),
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            {currentUserProfile?.metadata?.user_type === 'enduser' &&
              ![1, 2, 3, 4, 5].includes(record.trip_status) && (
                <>
                  {/* Nút Edit */}
                  <EditButton
                    text="Edit"
                    onClick={() => {
                      setCurrentRow(record); // record là dòng hiện tại trong table
                      setEditOpen(true);
                    }}
                  />

                  {/* Modal EditTrip */}
                  {editOpen && currentRow && (
                    <EditTrip
                      id={currentRow.id} // id chuyến đi
                      ship_id={currentRow.ship_id} // truyền ship_id
                      record={record} // truyền luôn cả record nếu cần
                      open={editOpen}
                      onOpenChange={setEditOpen}
                      onSuccess={() => {
                        setEditOpen(false);
                        setCurrentRow(undefined); // clear sau khi đóng
                        actionRef.current?.reload();
                      }}
                    />
                  )}

                  <Divider type="vertical" />
                </>
              )}

            {/* <LocationButton
              text={intl.formatMessage({
                id: "pages.things.location.text",
                defaultMessage: "Location",
              })}
              onClick={() => {
                setDataForMap(record);
                console.log("Data for map:", record);
                setCurrentRow(record);
                handleLocationModalVisible(true);
              }}
            />
            <Divider type="vertical" /> */}

            <TripCrews
              record={record}
              onChange={(items) => console.log(items)}
            />

            <Divider type="vertical" />

            {![0].includes(record.trip_status) &&
              currentUserProfile?.metadata?.user_type === 'enduser' && (
                <>
                  <DeleteButton
                    title={intl.formatMessage({
                      id: 'pages.trips.cancel.text',
                      defaultMessage: 'Cancel Trip',
                    })}
                    text="Hủy"
                    onOk={async () => {
                      // Thêm logic hủy chuyến đi
                      actionRef.current?.reload();
                    }}
                  />
                </>
              )}
          </>
        );
      },
    },
  ];

  return (
    <ProCard colSpan={{ xs: 24, sm: 24, md: 24, lg: 24, xl: 24 }}>
      <ProTable<SgwModel.Trip>
        columns={columns}
        tableLayout="auto"
        actionRef={actionRef}
        rowKey="id"
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        pagination={{
          pageSize: DEFAULT_PAGE_SIZE * 2,
          showSizeChanger: false,
          showTotal: (total, range) => `${range[0]}-${range[1]} trên ${total}`,
        }}
        request={async (params) => {
          const {
            current = 1,
            pageSize = DEFAULT_PAGE_SIZE * 2,
            name,
            trip_status,
            departure_time,
          } = params;
          const offset = current === 1 ? 0 : (current - 1) * pageSize;

          const query: SgwModel.TripQueryParams = {
            name: name || '',
            order: '',
            dir: 'desc',
            offset,
            limit: pageSize,
            metadata: {
              from: departure_time?.[0]
                ? dayjs(departure_time[0]).toISOString()
                : '',
              to: departure_time?.[1]
                ? dayjs(departure_time[1]).toISOString()
                : '',
              ship_name: '',
              reg_number: '',
              province_code: '',
              owner_id: '',
              ship_id: '',
              status: trip_status ? String(trip_status) : '',
            },
          };

          try {
            const response = await apiQueryTrips(query);

            return {
              success: true,
              data: response.trips || [],
              total: response.total || 0,
            };
          } catch (error) {
            console.error('Query trips error:', error);
            return {
              success: false,
              data: [],
              total: 0,
            };
          }
        }}
        toolbar={{
          // title: (
          //   <div
          //     style={{ display: "flex", alignItems: "center", gap: 8 }}
          //   >
          //     {selectedThingId ? (
          //       <Tag
          //         style={{
          //           cursor: "pointer",
          //           fontSize: "12px",
          //           padding: "4px 8px",
          //           lineHeight: "20px",
          //           minWidth: "0",
          //           overflow: "hidden",
          //           textOverflow: "ellipsis",
          //         }}
          //         onClick={(e) => {
          //           e.stopPropagation();
          //           setOpenFormSearch(true); // Mở lại modal chọn tàu
          //         }}
          //         closeIcon
          //         onClose={(e) => {
          //           e.stopPropagation();
          //           setselectedThingId(null);
          //           setFormSearchData(null);
          //           if (actionRef.current) {
          //             actionRef.current.reload();
          //           }
          //         }}
          //         color="#87d068"
          //       >
          //         {
          //           thingsList.find((s) => s.id === selectedThingId)
          //             ?.metadata?.ship_name
          //         }
          //       </Tag>
          //     ) : (
          //       <Button onClick={() => setOpenFormSearch(true)}>
          //         Chọn tàu
          //       </Button>
          //     )}
          //   </div>
          // ),
          actions: [
            <CreateTrip
              key="create-trip"
              // ship_name={
              //   thingsList.find((s) => s.id === selectedThingId)?.name
              // }
              // thing_id={selectedThingId}
              // record={currentRow}
              onSuccess={(value) => {
                if (value) {
                  actionRef.current?.reload();
                }
              }}
            />,
          ],
        }}
      />
    </ProCard>
  );
};

export default TripList;
