'use client';
import React, { useEffect, useState, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Avatar, Button, Card, Descriptions, Space, Spin, Tag, Typography, notification } from 'antd';
import { LockOutlined, UserOutlined, CameraOutlined } from '@ant-design/icons';
import type { AppDispatch, RootState } from '@/store/store';
import { useSession } from 'next-auth/react';
import { fetchUserProfile } from './slice';
import ChangePasswordModal from './components/Change-Password';
import { displayDate, getRoleIdMap } from '@/utills/helper';
import { fetchRoles } from '@/app/role/slice';
import { uploadProfilePhoto } from './service';
import { useRoles } from '@/hooks/useRoles';

const { Title } = Typography;

const ProfilePage: React.FC = () => {
  const { data, update } = useSession();
  const [roleFilters, setRoleFilters] = useState<any>({
    page: 1,
    sortColumn: 'sort_order',
  });
  const { user }: any = useSelector((state: RootState) => state?.userProfile);
  const [isChangePasswordModalVisible, setChangePasswordModalVisible] = useState<boolean>(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [uploading, setUploading] = useState<boolean>(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dispatch: AppDispatch = useDispatch();
  const userId = data?.user.id;
  const { roles } = useSelector((state: RootState) => state.roles);
  useEffect(() => {
    if(roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  let allRoles = getRoleIdMap(roles);
  const { getRoleByName } = useRoles();

  useEffect(() => {
    if (userId !== undefined && userId !== null) {
      getUserData();
    }
  }, [userId]);
  const showChangePasswordModal = (): void => {
    setChangePasswordModalVisible(true);
  };

  const handleCancelChangePassword = (): void => {
    setChangePasswordModalVisible(false);
  };

  const handleOkChangePassword = (): void => {
    setChangePasswordModalVisible(false);
  };
  const getUserData = (): void => {
    if (userId !== undefined && userId !== null) {
      dispatch(fetchUserProfile(userId));
    }
  };

  const validateImage = (file: File): string | null => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
      return 'Please select a valid image file (JPEG, PNG, GIF)';
    }

    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      return 'Image size must be less than 5MB';
    }

    return null;
  };

  const handleFileChange = async(e: React.ChangeEvent<HTMLInputElement>): Promise<void> => {
    const file = e.target.files?.[0];
    if (!file || !userId) return;

    const validationError = validateImage(file);
    if (validationError) {
      notification.error({
        message: 'Validation Error',
        description: validationError,
      });
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
      return;
    }

    setSelectedFile(file);

    // Show preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreviewUrl(reader.result as string);
    };
    reader.readAsDataURL(file);

    // Auto upload
    try {
      setUploading(true);
      const formData = new FormData();
      formData.append('profile_photo', file);
      formData.append('user_id', userId.toString());

      const response = await uploadProfilePhoto(userId, formData);

      notification.success({
        message: 'Success',
        description: 'Profile photo updated successfully',
      });

      // Update session with new profile photo so header updates immediately
      const newProfilePhoto = response?.url || response?.data?.profile_photo || response?.profile_photo;
      if (newProfilePhoto) {
        await update({ profile_photo: newProfilePhoto });
      }

      dispatch(fetchUserProfile(userId));

      setSelectedFile(null);
      setPreviewUrl(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } catch (error: any) {
      const message = error?.response?.data?.message || 'Failed to upload profile photo';
      notification.error({
        message: 'Upload Failed',
        description: message,
      });
      setSelectedFile(null);
      setPreviewUrl(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } finally {
      setUploading(false);
    }
  };

  const handleChangePhotoClick = (): void => {
    fileInputRef.current?.click();
  };

  return (
    <div>
      <div className="page-header">
        <Title level={2}>Profile</Title>
        <Space size="middle">
          <Button
            type="primary"
            icon={<LockOutlined />}
            onClick={() => {
              showChangePasswordModal();
            }}>
                        Change Password
          </Button>
        </Space>
      </div>
      {user ? (
        <Card title="Details">
          <div style={{ textAlign: 'center', marginBottom: '24px' }}>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/jpeg,image/png,image/jpg,image/gif"
              style={{ display: 'none' }}
              onChange={handleFileChange}
            />
            <Spin spinning={uploading}>
              <Avatar
                size={120}
                src={previewUrl || (user?.profile_photo ? `${process.env.BUCKET_URL}${user.profile_photo}` : undefined)}
                icon={<UserOutlined />}
                style={{ marginBottom: '16px' }}
              />
            </Spin>
            <div>
              <Button
                type="default"
                icon={<CameraOutlined />}
                onClick={handleChangePhotoClick}
                disabled={uploading}
                loading={uploading}>
                {uploading ? 'Uploading...' : 'Change Photo'}
              </Button>
            </div>
          </div>
          <Descriptions
            column={{ md: 1, lg: 2, xl: 2, xxl: 2 }}
            colon={true}
            size="middle"
            className="custom-descriptions"
            bordered>
            <React.Fragment key={user.id}>
              <Descriptions.Item label="Name:">
                {user?.first_name} {user?.last_name}
              </Descriptions.Item>
              <Descriptions.Item label="Email:">{user?.email}</Descriptions.Item>
              <Descriptions.Item label="Phone:">{user?.phone}</Descriptions.Item>
              {user?.role_id !== getRoleByName('super_admin')?.id && (
                <Descriptions.Item label="Cities:">
                  {user?.user_cities?.map((city: { city_name: string; }) => city?.city_name).join(', ')}
                </Descriptions.Item>
              )}
              {user?.role_id !== getRoleByName('super_admin')?.id && (
                <Descriptions.Item label="Designation:">
                  {user?.designation_name}
                </Descriptions.Item>
              )}
              {user?.reporting_manager_name && (
                <Descriptions.Item label="Reporting Manager:">
                  {user?.reporting_manager_name
                    ? user.reporting_manager_name
                    : '-'}
                                    ({user?.reporting_manager_role_label})
                </Descriptions.Item>
              )}

              <Descriptions.Item label="Account Created On:">
                {displayDate(user?.created_at)}
              </Descriptions.Item>
              {user?.role_id !== getRoleByName('super_admin')?.id && (
                <Descriptions.Item label="Account Created By:">
                  {user?.created_by_name} ({user?.created_by_role_label})
                </Descriptions.Item>
              )}
              <Descriptions.Item label="Status:" className="capitalize">
                <Tag
                  color={user?.status === 'active' ? 'green' : 'red'}
                  className="capitalize">
                  {user?.status}
                </Tag>
              </Descriptions.Item>
            </React.Fragment>
          </Descriptions>
        </Card>
      ) : null}
      {isChangePasswordModalVisible && (
        <ChangePasswordModal
          userId={userId}
          visible={isChangePasswordModalVisible}
          onCancel={handleCancelChangePassword}
          onOk={handleOkChangePassword}
        />
      )}
    </div>
  );
};

export default ProfilePage;
