'use client';
import React, { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useSearchParams } from 'next/navigation';
import { Steps, Form, Button, Card, Spin, notification } from 'antd';
import PageHeader from '@/components/pageHeader';
import LaunchDetails from '../components/LaunchDetail';
import TeamAssociation from '../components/TeamAssociation';
import { getLaunch } from '../service';
import { RootState, AppDispatch } from '@/store/store';
import { fetchRoles } from '@/app/role/slice';
import { useSelector, useDispatch } from 'react-redux';

import type {
  LaunchTeamI,
  launchSalesI,
  launchValuesI,
} from '../interface';
import { getRoleIdMap } from '@/utills/helper';
import { useRoles } from '@/hooks/useRoles';

const { Step } = Steps;

export interface storeDataI {
  lead_count?: number
  disableCityDropdown: boolean
  id?: number
  name?: string
  location?: string
  project_id?: [number, number]
  pairs?: launchSalesI[]
  data?: Record<string, unknown>;
  launch_projects?: Array<{ value: number; label: string }>
  launch_sales?: LaunchTeamI[]
  city_id?: number | string
  status?: string
  team_lead_id?: number | string
  cluster_manager_id?: number | string
  locality_name?: string,
  managers?: Array<{ role_id: number; role_name: string; user_id: number; user_name?: string; status?: string; is_blocked?: boolean }>
  is_sustenance?: number
}

const AddEditLaunch = () => {
  const { data } = useSession();
  const [form] = Form.useForm();
  const dispatch: AppDispatch = useDispatch();
  const searchParams = useSearchParams();
  const [storeData, setStoreData] = useState<storeDataI>({ disableCityDropdown: false });
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [submitionLoading, setSubmitionLoading] = useState<boolean>(false);
  const [launchLoading, setLaunchLoading] = useState<boolean>(false);
  // Parse launch ID from search params
  const parsedId = searchParams.get('id');
  const id = parsedId !== null && parsedId !== undefined ? parseInt(parsedId, 10) : undefined;
  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]);
  const allRoles = getRoleIdMap(roles);
  const { getRoleByName } = useRoles();

  useEffect(() => {
    // Fetch launch data if ID exists, otherwise prepare for new launch creation
    if (id !== undefined && id !== null) {
      setLaunchLoading(true);
      getLaunch(id)
        .then((res) => {
          setLaunchLoading(false);
          const launchData = res?.data;
          const formData = {
            ...launchData,
            team_lead_id:
              launchData.team_lead_id === 0 ? undefined : launchData.team_lead_id,
          };
          setStoreData({ ...formData, disableCityDropdown: true, is_sustenance: launchData.is_sustenance ? 1 : 0 });

          form.setFieldsValue(formData);
        })
        .catch((error) => {
          setLaunchLoading(false);
          console.error('error', error);
        });
    } else {
      // Prepare for new launch creation with default city ID
      setStoreData((formData) => ({ ...formData, disableCityDropdown: false, is_sustenance: 0 }));
      form.setFieldsValue({
        city_id: data?.user.cities[0]?.city_id,
      });
    }
    // Pre select cluster manager ID if current user is a cluster manager
    if (data?.user.role?.id === getRoleByName('cluster_manager')?.id) {
      form.setFieldsValue({
        cluster_manager_id: data?.user.id,
      });
    }
  }, [id]);

  const handlePrev = (): void => {
    setCurrentStep(currentStep - 1);
  };

  const onFinish = (values: launchValuesI): void => {
    const data: storeDataI = { ...storeData, ...values };
    setStoreData({ ...data, disableCityDropdown: true });
    if (currentStep === 0) {
      setCurrentStep(currentStep + 1);
    }
  };

  return (
    <div>
      <PageHeader
        title={id !== null && id !== undefined
          ? <span>Edit Launch{storeData.name ? <span style={{ fontSize: '25px' }}> ({storeData.name})</span> : ''}</span>
          : 'Create New Launch'}
      />
      <Steps
        current={currentStep}
        size="small"
        style={{ maxWidth: '500px', margin: '0 auto 29px auto' }}>
        <Step title="Launch Details" />
        <Step title="Team Association" />
      </Steps>
      <Card>
        <Form layout="vertical" form={form} onFinish={onFinish} preserve={true}>
          {!launchLoading ? (
            <>
              {currentStep === 0 && (
                <LaunchDetails
                  {...{
                    form,
                    userData: data,
                    storeData,
                    setStoreData,
                  }}
                />
              )}

              {currentStep > 0 && (
                <div style={{ position: 'absolute', bottom: '24px', left: '24px' }}>
                  <Button
                    type="primary"
                    ghost
                    style={{ marginRight: '8px' }}
                    onClick={handlePrev}
                    icon={<ArrowLeftOutlined />}>
                    Previous
                  </Button>
                </div>
              )}
            </>
          ) : (
            <Spin />
          )}
        </Form>
        {currentStep === 1 && (
          <TeamAssociation
            {...{
              setStoreData,
              form,
              submitionLoading,
              setSubmitionLoading,
              userData: data,
              storeData,
              currentStep,
              id,
              managers: storeData?.managers ?? [],
              cityHasChanged: false,
            }}
          />
        )}
      </Card>
    </div>
  );
};

export default AddEditLaunch;
