import { useCallback, useEffect, useState } from 'react';

export interface DocumentLockStatus {
  isLocked: boolean;
  lockedBy?: {
    userName: string;
    lockedAt: string;
  };
  lockError?: string;
  showLockMessage?: boolean;
}

type UseDocumentLockOptions = {
  enabled?: boolean;
};

export function useDocumentLock(documentType: string, documentId: string, options: UseDocumentLockOptions = {}) {
  const [lockStatus, setLockStatus] = useState<DocumentLockStatus>({ isLocked: false });
  const [isAcquiring, setIsAcquiring] = useState(false);
  const enabled = options.enabled ?? Boolean(documentType && documentId);

  const acquireLock = useCallback(async () => {
    if (!enabled || !documentType || !documentId) return true;

    setIsAcquiring(true);
    try {
      const response = await fetch('/api/document-locks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'acquire',
          documentType,
          documentId,
        }),
      });

      const data = await response.json();
      const showLockMessage = data.showEditingMessageToUser !== false;

      if (!response.ok) {
        setLockStatus({
          isLocked: false,
          lockError: data?.error || 'حدث خطأ أثناء محاولة قفل السند',
          showLockMessage,
        });
        return false;
      }

      if (!data.success) {
        setLockStatus({
          isLocked: true,
          lockError: showLockMessage ? 'تم قفل هذا السند من قبل مستخدم آخر' : undefined,
          lockedBy: data.lockedBy,
          showLockMessage,
        });
        return false;
      }

      setLockStatus({ isLocked: false, showLockMessage });
      return true;
    } catch (error) {
      console.error('Error acquiring lock:', error);
      setLockStatus({
        isLocked: false,
        lockError: 'حدث خطأ أثناء محاولة قفل السند',
        showLockMessage: true,
      });
      return false;
    } finally {
      setIsAcquiring(false);
    }
  }, [documentType, documentId, enabled]);

  const checkLock = useCallback(async () => {
    if (!enabled || !documentType || !documentId) return;

    try {
      const response = await fetch('/api/document-locks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'check',
          documentType,
          documentId,
        }),
      });

      const data = await response.json();
      const showLockMessage = data.showEditingMessageToUser !== false;

      if (!response.ok) {
        setLockStatus({
          isLocked: false,
          lockError: data?.error || 'حدث خطأ أثناء فحص القفل',
          showLockMessage,
        });
        return;
      }

      setLockStatus({
        isLocked: data.isLocked,
        lockError: data.isLocked && showLockMessage ? 'تم قفل هذا السند من قبل مستخدم آخر' : undefined,
        lockedBy: data.lock
          ? {
              userName: data.lock.userName || data.lock.user_name,
              lockedAt: data.lock.lockedAt || data.lock.locked_at,
            }
          : undefined,
        showLockMessage,
      });
    } catch (error) {
      console.error('Error checking lock:', error);
    }
  }, [documentType, documentId, enabled]);

  const releaseLock = useCallback(async () => {
    if (!enabled || !documentType || !documentId) return;

    try {
      await fetch('/api/document-locks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'release',
          documentType,
          documentId,
        }),
      });
    } catch (error) {
      console.error('Error releasing lock:', error);
    }
  }, [documentType, documentId, enabled]);

  // Acquire lock on mount
  useEffect(() => {
    if (!enabled) {
      setLockStatus({ isLocked: false });
      return;
    }

    acquireLock();

    // Cleanup: release lock on unmount
    return () => {
      releaseLock();
    };
  }, [acquireLock, enabled, releaseLock]);

  // Refresh lock status every 5 minutes
  useEffect(() => {
    if (!enabled) return;

    const interval = setInterval(() => {
      checkLock();
    }, 5 * 60 * 1000);

    return () => clearInterval(interval);
  }, [checkLock, enabled]);

  return { lockStatus, acquireLock, checkLock, releaseLock, isAcquiring };
}
