'use client';
import React, { useEffect, useRef, useState } from 'react';
import { Col, Row, Table, Tabs, TabsProps, Typography } from 'antd';
import { AppDispatch, RootState } from '@/store/store';
import { useDispatch, useSelector } from 'react-redux';
import {
  fetchDashboardSourceQuality,
  fetchSourceQualityTeamLead,
  setSourceQualityTabs,
} from '../slice';
import { ColumnsType } from 'antd/es/table';
import { dashboardSourceEfficiency } from '../interface';
import Highcharts from 'highcharts';
import { TablePaginationConfig } from 'antd/lib';
const { Title, Text } = Typography;

interface Props {
  roles: {
    roleId: number | undefined;
    defaultRoles: Record<string, number>;
  };
  loading?: boolean;
  onLoaded?: () => void;
}

const SourceQuality: React.FC<Props> = ({ roles, loading, onLoaded }) => {
  const refContainer = useRef(null);
  const dispatch: AppDispatch = useDispatch();
  const {
    dashboardSourceQuality,
    dashboardSourceQualityTableHeader,
    dashboardSourceQualityGraphData,
    sourceQualityTeamLead,
    sourceQualityTeamLeadTableHeader,
    sourceQualityTeamLeadGraphData,
    dashboardSourceQualityTab,
    dashboardFilter,
  } = useSelector((state: RootState) => state.dashboard);

  // Pagination state and change handlers
  const [paginationVisited, setPaginationVisited] = useState({ current: 1, pageSize: 10 });
  const [paginationToken, setPaginationToken] = useState({ current: 1, pageSize: 10 });
  const [paginationBooked, setPaginationBooked] = useState({ current: 1, pageSize: 10 });

  // Determine table data based on user role
  let tableData;
  if (roles?.roleId === roles?.defaultRoles.team_lead) {
    if (sourceQualityTeamLead) {
      tableData = [...sourceQualityTeamLead];
      tableData.sort((a, b) => a?.project_name.localeCompare(b?.project_name));
    }
  } else {
    if (dashboardSourceQuality) {
      tableData = [...dashboardSourceQuality];
      tableData.sort((a, b) => a?.launch_name.localeCompare(b?.launch_name));
    }
  }

  // Determine table header based on user role
  const tableHeader =
        roles?.roleId === roles?.defaultRoles.team_lead
          ? sourceQualityTeamLeadTableHeader
          : dashboardSourceQualityTableHeader;
  // Determine graph data based on user role
  const graphData =
        roles?.roleId === roles?.defaultRoles.team_lead
          ? sourceQualityTeamLeadGraphData
          : dashboardSourceQualityGraphData;

  // Initialize Highcharts chart
  useEffect(() => {
    if (!refContainer.current || !Array.isArray(graphData) || graphData.length === 0) {
      return;
    }
    const categories = Array.from(new Set(graphData.map(item => item?.type)));
    const seriesData = graphData?.reduce((acc, item) => {
      const existingSeries = acc?.find((series: { name: string; }) => series?.name === item?.name);
      if (existingSeries) {
        existingSeries.data[categories?.indexOf(item?.type)] = item?.launchs;
      } else {
        const newData = Array(categories?.length)?.fill(0);
        newData[categories?.indexOf(item?.type)] = item?.launchs;
        acc.push({ name: item?.name, data: newData });
      }
      return acc;
    }, []);

    const chart = Highcharts?.chart(refContainer.current, {
      chart: {
        type: 'column',
      },
      title: {
        text: '',
      },
      subtitle: {
        text: '',
      },
      xAxis: {
        categories: categories,
        crosshair: true,
      },
      yAxis: {
        min: 0,
        title: {
          text: '',
        },
      },
      credits: {
        enabled: false,
      },
      legend: {
        layout: 'horizontal',
        align: 'center',
        verticalAlign: 'bottom',
        y: 0,
      },
      series: seriesData?.map((series: Object) => ({
        ...series,
        pointWidth: 30,
      })),
      responsive: {
        rules: [{
          condition: {
            maxWidth: 800,
          },
          chartOptions: {
            series: seriesData?.map((series: Object) => ({
              ...series,
              pointWidth: 15,
            })),
            legend: {
              enabled: true,
              maxHeight: 70,
              itemWidth: 150,
            },
          },
        }],
      },
    });

    if (graphData.length > 0) {
      chart.hideLoading();
    } else {
      chart.showLoading();
    }
  }, [graphData]);

  // Fetch source quality data based on user role
  const handleDashboardSourceQualityData = () => {
    if (roles?.roleId === roles?.defaultRoles.team_lead) {
      dispatch(fetchSourceQualityTeamLead({}));
    } else {
      dispatch(fetchDashboardSourceQuality({}));
    }
  };

  const handleSourceQualityTab = (value: string) => {
    dispatch(setSourceQualityTabs(value));
  };

  const handleTableChangeVisited = (pagination: TablePaginationConfig) => {
    setPaginationVisited(pagination as { current: number; pageSize: number });
  };

  const handleTableChangeToken = (pagination: TablePaginationConfig) => {
    setPaginationToken(pagination as { current: number; pageSize: number });
  };

  const handleTableChangeBooked = (pagination: TablePaginationConfig) => {
    setPaginationBooked(pagination as { current: number; pageSize: number });
  };

  useEffect(() => {
    handleDashboardSourceQualityData();
  }, [
    dashboardSourceQualityTab,
    dashboardFilter.launch_id,
    dashboardFilter.lead_user_city_id,
    dashboardFilter.lead_user_id,
    dashboardFilter.lead_user_role_name,
    dashboardFilter?.veiw_data,
  ]);

  // Call onLoaded when data is loaded and chart is rendered
  useEffect(() => {
    const isLoaded = Array.isArray(graphData) && graphData.length > 0 && !loading;
    if (isLoaded && typeof onLoaded === 'function') {
      onLoaded();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [graphData, loading]);

  const columns: ColumnsType<dashboardSourceEfficiency> = [
    {
      title:
                roles?.roleId === roles?.defaultRoles.team_lead
                  ? 'Project / Source'
                  : 'Launch / Source',
      dataIndex:
                roles?.roleId === roles?.defaultRoles.team_lead ? 'project_name' : 'launch_name',
      key:
                roles?.roleId === roles?.defaultRoles.team_lead ? 'project_name' : 'launch_name',
      align: 'left',
      width: 200,
      fixed: 'left',
    },
    ...tableHeader.map((item: ColumnsType) => ({
      ...item,
      render: (data: { value: string; color: string }) => (
        <Text style={{ color: data?.color || 'inherit' }}>{data?.value || '0%'}</Text>
      ),
    })),
  ];
  // Source Quality Tabs Content
  const sourceQualityItems: TabsProps['items'] = [
    {
      key: 'visited',
      label: 'Visits',
      children: (
        <>
          {graphData.length > 0 ? (
            <div className="dashboard-graph-container">
              <div ref={refContainer} />
            </div>
          ) : null}
          <Table
            bordered
            tableLayout="fixed"
            pagination={{ ...paginationVisited }}
            onChange={handleTableChangeVisited}
            scroll={{ x: true }}
            className="table-layout-fixed"
            dataSource={tableData}
            columns={columns}
          />
        </>
      ),
    },
    {
      key: 'token',
      label: 'Tokens',
      children: (
        <>
          {graphData.length > 0 ? (
            <div className="dashboard-graph-container">
              <div ref={refContainer} />
            </div>
          ) : null}
          <Table
            bordered
            tableLayout="fixed"
            pagination={{ ...paginationToken }}
            onChange={handleTableChangeToken}
            scroll={{ x: true }}
            className="table-layout-fixed"
            dataSource={tableData}
            columns={columns}
          />
        </>
      ),
    },
    {
      key: 'booked',
      label: 'Bookings',
      children: (
        <>
          {graphData.length > 0 ? (
            <div className="dashboard-graph-container">
              <div ref={refContainer} />
            </div>
          ) : null}
          <Table
            bordered
            tableLayout="fixed"
            pagination={{ ...paginationBooked }}
            onChange={handleTableChangeBooked}
            scroll={{ x: true }}
            className="table-layout-fixed"
            dataSource={tableData}
            columns={columns}
          />
        </>
      ),
    },
  ];
  return (
    <Row gutter={[40, 40]} className="mb-5">
      <Col span={24}>
        <div className="dashboard-section-header">
          <Title level={4}>Source Quality</Title>
        </div>
        <Tabs
          defaultActiveKey="visited"
          size="middle"
          items={sourceQualityItems}
          onChange={handleSourceQualityTab}
          className="custom-tabs-horizontal"
        />
      </Col>
    </Row>
  );
};
export default SourceQuality;