import { useState, useEffect, useCallback, useRef } from 'react';
import { IAuditLog, IUser } from '../types';
import { dataService } from '../services/dataService';
import { useAuthStore } from '../store/useAuthStore';
import { useUIStore } from '../store/useUIStore';

const LOGS_PER_PAGE = 50;

export const useProfileModal = () => {
  const { user, setUser } = useAuthStore();
  const { addNotification, isProfileModalOpen } = useUIStore();
  const [activeProfileTab, setActiveProfileTab] = useState<'info' | 'password' | 'logs'>('info');
  const [userLogs, setUserLogs] = useState<IAuditLog[]>([]);
  const [logPage, setLogPage] = useState(1);
  const [hasMoreLogs, setHasMoreLogs] = useState(true);
  const [isLoadingLogs, setIsLoadingLogs] = useState(false);
  const [expandedDates, setExpandedDates] = useState<Set<string>>(new Set());
  const logsLoadedRef = useRef(false);

  // Email Edit State
  const [isEditingEmail, setIsEditingEmail] = useState(false);
  const [editedEmail, setEditedEmail] = useState('');

  // Name Edit State
  const [isEditingName, setIsEditingName] = useState(false);
  const [editedName, setEditedName] = useState('');

  // Password Change State
  const [passwordForm, setPasswordForm] = useState({ current: '', new: '', confirm: '' });

  const loadLogs = useCallback(async (page: number) => {
    if (!user || isLoadingLogs) return;
    setIsLoadingLogs(true);
    try {
      const result = await dataService.getLogs(user._id, page, LOGS_PER_PAGE);
      if (result.data.length > 0) {
        setUserLogs(prev => page === 1 ? result.data : [...prev, ...result.data]);

        // Auto expand the first date group for the first load
        if (page === 1) {
          const firstDate = new Date(result.data[0].timestamp).toLocaleDateString('vi-VN');
          setExpandedDates(new Set([firstDate]));
        }

        if (result.pagination) {
          setHasMoreLogs(result.pagination.page < result.pagination.pages);
        } else {
          setHasMoreLogs(result.data.length === LOGS_PER_PAGE);
        }
      } else {
        setHasMoreLogs(false);
      }
      logsLoadedRef.current = true;
    } catch (error) {
      console.error('Failed to load logs:', error);
    } finally {
      setIsLoadingLogs(false);
    }
  }, [user]);

  const handleLoadMoreLogs = useCallback(() => {
    if (isLoadingLogs) return;
    const nextPage = logPage + 1;
    setLogPage(nextPage);
    loadLogs(nextPage);
  }, [logPage, loadLogs, isLoadingLogs]);

  const groupLogsByDate = useCallback((logs: IAuditLog[]) => {
    const groups: Record<string, IAuditLog[]> = {};
    logs.forEach(log => {
      const date = new Date(log.timestamp).toLocaleDateString('vi-VN');
      if (!groups[date]) groups[date] = [];
      groups[date].push(log);
    });
    return groups;
  }, []);

  const toggleDateExpansion = useCallback((date: string) => {
    setExpandedDates(prev => {
      const next = new Set(prev);
      if (next.has(date)) next.delete(date);
      else next.add(date);
      return next;
    });
  }, []);

  const handleChangePassword = useCallback(async () => {
    if (passwordForm.new !== passwordForm.confirm) {
      addNotification('error', 'Mật khẩu xác nhận không khớp.');
      return;
    }
    if (!user) return;

    const result = await dataService.changePassword(user._id, passwordForm.current, passwordForm.new);
    if (result.success) {
      addNotification('success', result.message);
      setPasswordForm({ current: '', new: '', confirm: '' });
    } else {
      addNotification('error', result.message);
    }
  }, [passwordForm, user, addNotification]);

  const handleUpdateEmail = useCallback(async () => {
    if (!user || !editedEmail) return;

    // Basic email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(editedEmail)) {
      addNotification('error', 'Định dạng email không hợp lệ.');
      return;
    }

    if (editedEmail === user.email) {
      setIsEditingEmail(false);
      return;
    }

    try {
      setIsLoadingLogs(true);
      const updatedUser = await dataService.updateUser({ ...user, email: editedEmail });
      setUser(updatedUser);
      addNotification('success', 'Cập nhật email thành công.');
      setIsEditingEmail(false);
    } catch (error: any) {
      addNotification('error', error.message || 'Cập nhật email thất bại.');
    } finally {
      setIsLoadingLogs(false);
    }
  }, [user, editedEmail, addNotification, setUser]);

  const handleUpdateName = useCallback(async () => {
    if (!user || !editedName || editedName.trim() === '') {
      addNotification('error', 'Tên không được để trống.');
      return;
    }

    if (editedName === user.name) {
      setIsEditingName(false);
      return;
    }

    try {
      setIsLoadingLogs(true);
      const updatedUser = await dataService.updateUser({ ...user, name: editedName.trim() });
      setUser(updatedUser);
      addNotification('success', 'Cập nhật tên thành công.');
      setIsEditingName(false);
    } catch (error: any) {
      addNotification('error', error.message || 'Cập nhật tên thất bại.');
    } finally {
      setIsLoadingLogs(false);
    }
  }, [user, editedName, addNotification, setUser]);

  // Reset logs when modal closes or when switching away from logs tab
  useEffect(() => {
    if (!isProfileModalOpen) {
      logsLoadedRef.current = false;
      setUserLogs([]);
      setLogPage(1);
      setHasMoreLogs(true);
      setExpandedDates(new Set());
    } else if (activeProfileTab !== 'logs') {
      // Reset flag when switching away from logs tab so it can reload when coming back
      logsLoadedRef.current = false;
    }
  }, [isProfileModalOpen, activeProfileTab]);

  // Load logs when switching to logs tab
  useEffect(() => {
    if (isProfileModalOpen && activeProfileTab === 'logs' && user && !logsLoadedRef.current && !isLoadingLogs) {
      logsLoadedRef.current = true;
      setUserLogs([]);
      setLogPage(1);
      setHasMoreLogs(true);
      loadLogs(1);
    }
  }, [isProfileModalOpen, activeProfileTab, user, loadLogs, isLoadingLogs]);

  useEffect(() => {
    if (isProfileModalOpen && user) {
      setEditedEmail(user.email);
      setEditedName(user.name);
      setIsEditingEmail(false);
      setIsEditingName(false);
    }
  }, [isProfileModalOpen, user]);

  return {
    activeProfileTab,
    setActiveProfileTab,
    userLogs,
    hasMoreLogs,
    isLoadingLogs,
    expandedDates,
    isEditingEmail,
    setIsEditingEmail,
    editedEmail,
    setEditedEmail,
    isEditingName,
    setIsEditingName,
    editedName,
    setEditedName,
    passwordForm,
    setPasswordForm,
    handleLoadMoreLogs,
    groupLogsByDate,
    toggleDateExpansion,
    handleChangePassword,
    handleUpdateEmail,
    handleUpdateName
  };
};
