'use client';
import React, { useEffect, useState } from 'react';
import { Form, Button, Select, Row, Col, Card, notification } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { fetchExistingUsers, fetchNewUsers } from './slice';
import MasterRoles from '@/components/masterDropdowns/MasterRoles';
import MasterCities from '@/components/masterDropdowns/MasterCities';
import { AppDispatch, RootState } from '@/store/store';
import { updateDeassociation } from './service';
import { useRoles } from '@/hooks/useRoles';

const { Option } = Select;
interface User {
  id: number;
  first_name: string;
  last_name: string;
}

interface FormValues {
  old_user: number;
  new_user: number;
  role_id: number;
  city_id: number;
}
const DissociationPage: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch<AppDispatch>();
  const { getRoleByName } = useRoles();

  // Get users data from Redux store
  const existingUsers = useSelector((state: RootState) => state.dissociation.existingUsers);
  const newUsers = useSelector((state: RootState) => state.dissociation.newUsers);

  const [roleId, setRoleId] = useState<string | number | undefined>();
  const [cityId, setCityId] = useState<string | number | undefined>();
  const [existingUserId, setExistingUserId] = useState<number | undefined>();
  const [submitionLoading, setSubmitionLoading] = useState<boolean>(false);

  // Fetch Existing Users when role_id and city_id change
  useEffect(() => {
    if (roleId && cityId) {
      dispatch(fetchExistingUsers({ role_id: roleId, city_id: cityId }));
    }
  }, [roleId, cityId, dispatch]);

  // Fetch New Users when existing_user_id changes
  useEffect(() => {
    if (roleId && cityId && existingUserId) {
      dispatch(fetchNewUsers({ role_id: roleId, city_id: cityId, user_id: existingUserId }));
    }
  }, [roleId, cityId, existingUserId, dispatch]);

  // Function to handle form submission
  const handleSubmit = (values: FormValues) => {
    setSubmitionLoading(true);
    updateDeassociation({
      old_user: values.old_user,
      new_user: values.new_user,
      role_id: values.role_id,
      city_id: values.city_id,
    })
      .then((response) => {
        if (response && response.message) {
          notification.success({
            message: 'Success',
            description: response.message,
          });
        }
        form.resetFields();
        setRoleId(undefined);
        setCityId(undefined);
        setExistingUserId(undefined);
      })
      .catch((error) => {
        const errorMessage = error?.response?.data?.message;
        notification.error({
          message: 'Error',
          description: errorMessage,
        });
      });
    setSubmitionLoading(false);
  };

  // Function to handle form cancellation
  const handleCancel = () => {
    form.resetFields();
    setRoleId(undefined);
    setCityId(undefined);
    setExistingUserId(undefined);
  };

  return (
    <Card title={'Dissociation'}>
      <Form form={form} onFinish={handleSubmit} layout="vertical">
        <Row gutter={16}>
          <Col xs={24} md={12}>
            <MasterRoles
              name="role_id"
              label="Role"
              rules={[{ required: true, message: 'Please Select a Role' }]}
              onChange={(value) => {
                form.setFieldsValue({
                  role_id: value,
                  city_id: undefined,
                  old_user: undefined,
                  new_user: undefined,
                });
                setRoleId(value);
                setCityId(undefined);
                setExistingUserId(undefined);
              }}
              onClear={() => {
                form.setFieldsValue({
                  role_id: undefined,
                  old_user: undefined,
                  new_user: undefined,
                });
                setRoleId(undefined);
                setCityId(undefined);
                setExistingUserId(undefined);
              }}
              exclude={[getRoleByName('super_admin')?.id, getRoleByName('city_head')?.id].filter(
                (id): id is number => id !== undefined,
              )}
            />
          </Col>

          <Col xs={24} md={12}>
            <MasterCities
              name="city_id"
              label="City"
              rules={[{ required: true, message: 'Please Select a City' }]}
              filter={{ status: 'active' }}
              onChange={(value) => {
                form.setFieldsValue({
                  city_id: value,
                  old_user: undefined,
                  new_user: undefined,
                });
                setCityId(value);
                setExistingUserId(undefined);
              }}
              onClear={() => {
                form.setFieldsValue({
                  city_id: undefined,
                  old_user: undefined,
                  new_user: undefined,
                });
                setCityId(undefined);
                setExistingUserId(undefined);
              }}
            />
          </Col>
        </Row>

        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col xs={24} md={12}>
            <Form.Item
              name="old_user"
              label="Old Employee"
              rules={[{ required: true, message: 'Please Select an Old Employee' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                onChange={(value) => {
                  form.setFieldsValue({ old_user: value,  new_user: undefined });
                  setExistingUserId(value);
                }}
                onClear={() =>
                  form.setFieldsValue({
                    old_user: undefined,
                    new_user: undefined,
                  })
                }
                allowClear
                placeholder="Select an Old Employee"
                disabled={!roleId || !cityId}>
                {existingUsers?.map((user: User) => (
                  <Option key={user.id} value={user.id}>
                    {user.first_name} {user.last_name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} md={12}>
            <Form.Item
              name="new_user"
              label="New Employee"
              rules={[{ required: true, message: 'Please Select a New Employee' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                onChange={(value) => form.setFieldsValue({ new_user: value })}
                onClear={() => form.setFieldsValue({ new_user: undefined })}
                placeholder="Select a New Employee"
                disabled={!existingUserId}>
                {newUsers?.map((user: User) => (
                  <Option key={user.id} value={user.id}>
                    {user.first_name} {user.last_name}
                  </Option>
                ))}
                                 allowClear
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item style={{ marginTop: 16, display: 'flex', justifyContent: 'end' }}>
          <Button type="primary" htmlType="submit" loading={submitionLoading}>
                        Submit
          </Button>
          <Button style={{ marginLeft: '8px' }} onClick={handleCancel}>
                        Cancel
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default DissociationPage;
