'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { EyeOutlined, EditOutlined } from '@ant-design/icons';
import { Table, Button, Space, Tag, Popover } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/navigation';
import { fetchLaunchs } from '../slice';
import FilterLaunch from './FilterLaunch';
import { displayDate } from '@/utills/helper';
import { LIST_META } from '@/utills/constant';
import type { ColumnsType } from 'antd/es/table';
import type { Launch, LaunchPayload, launchPaginationI, launchSorterI } from '../interface';
import { useSession } from 'next-auth/react';
import { RootState, type AppDispatch } from '@/store/store';

const LaunchPage: React.FC<{ isEditable?: boolean }> = ({
  isEditable,
}: {
    isEditable?: boolean
}) => {
  const router = useRouter();
  const dispatch: AppDispatch = useDispatch();
  const { data: session } = useSession();
  const userCities = session?.user.cities;
  const isSuperAdmin = session?.user?.role?.name === 'super_admin';
  
  const cityIdsKey = useMemo(() => userCities?.map((city) => city?.city_id).join(','), [userCities]);
  const launches = useSelector((state: any) => state?.launches?.launches?.data);
  const usersMeta = useSelector((state: RootState) => state.launches);
  const listLoading = useSelector((state: RootState) => state.launches.listLoading);
  const { status } = useSelector((state: RootState) => state.launches);

  const [filters, setFilters] = useState({
    page: 1,
    pageSize: LIST_META.per_page,
    pagination: true,
    search: '',
    location: '',
    created_by: undefined,
    city_id: undefined as string | undefined,
    status: '',
    sortColumn: 'name',
    sortOrder: 'asc',
  });

  useEffect(() => {
    const defaultCityId = cityIdsKey;

    if (defaultCityId) {
      setFilters((prev) => {
        if (prev.city_id === defaultCityId) {
          return prev;
        }

        const nextFilters = {
          ...prev,
          city_id: defaultCityId,
          page: 1,
        };
        getLaunchs(nextFilters);
        return nextFilters;
      });
      return;
    }

    getLaunchs({
      page: 1,
      pageSize: LIST_META.per_page,
      sortColumn: '',
      sortOrder: '',
    });
  }, [cityIdsKey]);

  const getLaunchs = (filter: LaunchPayload): void => {
    dispatch(fetchLaunchs(filter));
  };

  const handleTableChange = (
    pagination: launchPaginationI,
    sorter: launchSorterI
  ): void => {
    const newFilters = {
      ...filters, // Start with current filters state
      page: pagination.current,
      pageSize: pagination.pageSize,
    };

    if (sorter?.order === 'ascend') {
      newFilters.sortOrder = 'asc';
      newFilters.sortColumn = sorter?.field ?? '';
    } else if (sorter?.order === 'descend') {
      newFilters.sortOrder = 'desc';
      newFilters.sortColumn = sorter?.field ?? '';
    } else {
      newFilters.sortOrder = '';
      newFilters.sortColumn = '';
    }
    setFilters(newFilters);
    getLaunchs(newFilters);
  };

  const columns: ColumnsType<Launch> = [
    {
      title: 'Launch Name',
      dataIndex: 'name',
      key: 'name',
      width: 280,
    },
    // {
    //   title: 'Project Count',
    //   dataIndex: 'project_count',
    //   key: 'project_count',
    //   width: 150,
    //   className: 'nowrap',
    //   align: 'center',
    //   render: (project_count: number, record) => (
    //     <Popover
    //       content={
    //         record.launch_projects &&
    //                     record.launch_projects?.map((item) => <div key={item.project_name}>{item.project_name}</div>)
    //       }
    //       placement="topRight"
    //     >
    //       <span>{project_count || 0}</span>
    //     </Popover>
    //   ),
    //   sortDirections: ['ascend', 'descend'],
    //   sorter: true,
    // },
    {
      title: 'Location',
      dataIndex: 'location',
      key: 'location',
      width: 200,
    },

    {
      title: 'Created By',
      dataIndex: 'created_by_name',
      key: 'created_by_name',
      width: 150,
    },
    {
      title: 'Created On',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      align: 'center',
      sorter: (a, b) => a.created_at?.localeCompare(b.created_at),
      sortDirections: ['ascend', 'descend'],
      render: (text, record) => displayDate(record.created_at),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status: string) => (
        <Tag color={status === 'On' ? 'green' : 'red'}>{status}</Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      className: 'nowrap',
      align: 'center',
      render: (record) => (
        <Space size="small">
          <Button
            type="primary"
            shape="circle"
            icon={<EyeOutlined />}
            size="middle"
            onClick={() => {
              router.push(`/launches/view-edit-launch/${record.id}`);
            }}
            title="View"
          />
          {isEditable && (
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                router.push(`/launches/add-launch?id=${record.id}`);
              }}
              size="middle"
              title="Edit"
            />
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FilterLaunch
        onSearch={(filter) => {
          const newFilters = {
            ...filters,
            ...filter,
            page: 1, // Reset to page 1 on new search
          };
          setFilters(newFilters);
          getLaunchs(newFilters);
        }}
        defaultFilter={{
          cities: userCities,
        }}
        status={status}
        isSuperAdmin={isSuperAdmin}
      />
      <Table
        dataSource={launches}
        rowKey="id"
        columns={columns}
        bordered
        loading={listLoading}
        tableLayout="fixed"
        scroll={{ x: true }}
        className="table-layout-fixed"
        pagination={{
          current: usersMeta?.launchMeta?.current_page,
          pageSize: usersMeta?.launchMeta?.per_page,
          total: usersMeta?.launchMeta?.total,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100'],
          defaultPageSize: 10,
          showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} entries`,
        }}
        onChange={(pagination: any, tableFilters: any, sorter: any) => {
          // Ant Design's tableFilters are ignored as per instruction,
          // as the component's 'filters' state is the single source of truth.
          handleTableChange(pagination, sorter);
        }}
      />
    </div>
  );
};

export default LaunchPage;
