'use client';
import { Table, Button, Space, Form, Radio, notification, Popconfirm, Spin, RadioChangeEvent } from 'antd';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from '@/store/store';
import { fetchAllLeadRequests } from './slice';
import { type SortOrder } from 'antd/lib/table/interface';
import FilterLeadRequests from './components/Filter';
import { updateLeadStatus } from './service';
import type { FilterOptions } from './interface';
import { displayDate, getRoleIdMap } from '@/utills/helper';
import { useSession } from 'next-auth/react';
import PageHeader from '@/components/pageHeader';
import { fetchRoles } from '@/app/role/slice';
import { useRoles } from '@/hooks/useRoles';

const AllLeadRequestPage: React.FC = () => {
  const dispatch: AppDispatch = useDispatch();
  const { leadRequests, leadsMeta } = useSelector((state: RootState) => state.leadRequests);
  const { data: session } = useSession();
  const user = session?.user;

  const [filters, setFilters] = useState<FilterOptions>({
    status: 'pending',
    page: 1,
    pageSize: 10,
    sortColumn: '',
    sortOrder: '',
  });

  const [roleFilters, setRoleFilters] = useState<any>({
    page: 1,
    sortColumn: 'sort_order',
  });
  const { roles } = useSelector((state: RootState) => state.roles);
  useEffect(() => {
    if(roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  let allRoles = getRoleIdMap(roles);
  const { getRoleByName } = useRoles();
  const [loading, setLoading] = useState(false);

  // Fetch leads on initial load and whenever filters change
  useEffect(() => {
    fetchLeads();
  }, [filters]);

  // Handle radio button change for status filter
  const handleRadioChange = (e: RadioChangeEvent): void => {
    setLoading(true);
    // Optionally, you can reset other filters when the radio button changes
    setFilters({
      ...filters,
      page: 1,
      // search: '',
      status: e.target.value,
    });
  };

  // Fetch leads based on current filters
  const fetchLeads = (): void => {
    dispatch(fetchAllLeadRequests(filters))
      .then(() => setLoading(false))
      .catch(() => setLoading(false));
  };

  // Update lead status to 'approved'
  const handleApprove = (leadId: number) => {
    updateLeadStatus(leadId, 'approved')
      .then(() => {
        notification.success({
          message: 'Success',
          description: 'Lead request approved successfully.',
        });
        fetchLeads();
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error.response.data.message,
        });
        console.error('Error approving lead:', error);
      });
  };

  // Update lead status to 'rejected'
  const handleReject = (leadId: number) => {
    updateLeadStatus(leadId, 'reject')
      .then(() => {
        notification.success({
          message: 'Success',
          description: 'Lead request rejected successfully.',
        });
        fetchLeads();
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error.response.data.message,
        });
        console.error('Error rejecting lead:', error);
      });
  };

  // Button click event handler for approving a lead
  const handleApproveButtonClick = (id: number) => {
    handleApprove(id); // Get the leadId from your data or state;
  };

  // Example button click event for rejection
  const handleRejectButtonClick = (id: number) => {
    handleReject(id); // Get the leadId from your data or state;
  };

  // Handle search with new filters
  const handleSearch = (filter: FilterOptions): void => {
    setFilters({
      ...filters,
      ...filter,
      page: 1, // Reset the page to 1 when a new search is performed
    });
  };
  const handleTableChange = (pagination: { current: number; pageSize: number }, filters: FilterOptions, sorter: { field: string; order: 'ascend' | 'descend' }): void => {
    // Extract relevant information from Ant Design Table's parameters
    const { current, pageSize } = pagination;
    const { field, order } = sorter;

    const newFilters = {
      ...filters,
      page: current,
      pageSize,
      sortColumn: field ?? '',
      sortOrder: order === 'ascend' ? 'asc' : 'desc',
      status: filters?.status,
    };

    setFilters(newFilters);
    fetchLeads();
  };

  // Define table columns based on lead status
  const columns = [
    {
      title: 'Launch Name',
      dataIndex: 'launch_name',
      key: 'launch_name',
      sorter: true,
      width: 200,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
    },
    {
      title: 'Project Name',
      dataIndex: 'project_name',
      key: 'project_name',
      sorter: true,
      width: 200,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
    },
    {
      title: 'Lead Status',
      dataIndex: 'lead_status_name',
      key: 'lead_status_name',
      sorter: true,
      width: 200,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
    },
    {
      title: 'Lead/Days',
      dataIndex: 'lead_count',
      key: 'lead_count',
      sorter: true,
      width: 115,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
    },
    {
      title: 'Lead Start Date',
      dataIndex: 'start_date',
      key: 'start_date',
      sorter: true,
      width: 170,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => <span>{displayDate(text)}</span>,
    },
    {
      title: 'Requested Date',
      dataIndex: 'created_at',
      key: 'created_at',
      sorter: true,
      width: 170,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => <span>{displayDate(text)}</span>,
    },
    {
      title: 'Requested By',
      dataIndex: 'created_by_name',
      sorter: true,
      width: 200,
      key: 'created_by_name',
      sortDirections: ['ascend', 'descend'] as SortOrder[],
    },
  ];

  if (filters.status === 'pending') {
    // columns.push()
    // columns.push()
  }
  if (filters.status === 'reject') {
    columns.push({
      title: 'Request Status',
      dataIndex: 'status',
      key: 'status',
      sorter: true,
      width: 170,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => (
        <span>{text.charAt(0).toUpperCase() + text.slice(1)}</span>
      ),
    });
    columns.push({
      title: 'Rejected Date',
      dataIndex: 'updated_at',
      key: 'updated_at',
      sorter: true,
      width: 170,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => <span>{displayDate(text)}</span>,
    });
  }

  if (filters.status === 'approved') {
    columns.push({
      title: 'Request Status',
      dataIndex: 'status',
      key: 'status',
      sorter: true,
      width: 170,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => (
        <span>{text.charAt(0).toUpperCase() + text.slice(1)}</span>
      ),
    });
    columns.push({
      title: 'Approved Date',
      dataIndex: 'updated_at',
      key: 'updated_at',
      sorter: true,
      width: 200,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (text: string) => <span>{displayDate(text)}</span>,
    });
  }

  if (
    [getRoleByName('city_head')?.id, getRoleByName('super_admin')?.id].includes(user?.role?.id || 0) &&
        filters.status === 'pending'
  ) {
    columns.push({
      title: 'Action',
      key: 'action',
      dataIndex: 'start_date',
      width: 200,
      sorter: false,
      sortDirections: ['ascend', 'descend'] as SortOrder[],
      render: (record: any) => (
        <span>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                handleApproveButtonClick(record.id);
              }}>
                            Approve
            </Button>
            <Popconfirm
              title="Are you sure you want to reject this request?"
              onConfirm={() => {
                handleRejectButtonClick(record.id);
              }}
              okText="Yes"
              cancelText="No"
              placement="topRight">
              <Button type="primary" danger>
                                Reject
              </Button>
            </Popconfirm>
          </Space>
        </span>
      ),
    });
  }

  return (
    <div>
      <PageHeader title="Lead Requests" isBack={false} />

      <FilterLeadRequests onSearch={handleSearch} cities={user?.cities} />

      <Form.Item>
        <Radio.Group
          onChange={handleRadioChange}
          value={filters.status}
          style={{ marginLeft: '8px' }}>
          <Radio value="pending">Pending</Radio>
          <Radio value="approved">Approved</Radio>
          <Radio value="reject">Rejected</Radio>
        </Radio.Group>
      </Form.Item>
      <div className="page-header"></div>
      {loading ? (
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <Spin size="large" />
        </div>
      ) : (
        <Table
          onChange={(pagination: any, tableFilters: any, sorter: any) => {
            const myTableFilter = {
              ...tableFilters,
              ...filters,
            };

            handleTableChange(pagination, myTableFilter, sorter);
          }}
          pagination={{
            current: leadsMeta?.current_page,
            pageSize: leadsMeta?.per_page,
            total: leadsMeta?.total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            defaultPageSize: 10,
            showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} entries`,
          }}
          rowKey="id"
          columns={
            filters.status === 'pending'
              ? columns.filter((col) => col.key !== 'approvedDate')
              : filters.status === 'approved'
                ? columns.filter(
                  (col) => col.key !== 'launchName' && col.key !== 'action'
                )
                : columns.filter(
                  (col) => col.key !== 'rejectedDate' && col.key !== 'action'
                ) // Show only rejected columns
          }
          dataSource={leadRequests}
          tableLayout="fixed"
          scroll={{ x: true }}
          className="table-layout-fixed"
          bordered
        />
      )}
    </div>
  );
};

export default AllLeadRequestPage;
