53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import React from 'react';
|
|
import { useSleepSession } from '../../hooks/useSleepSession';
|
|
|
|
interface SleepButtonProps {
|
|
time: string;
|
|
}
|
|
|
|
const SleepButton: React.FC<SleepButtonProps> = ({ time }) => {
|
|
const { activeSession, createSession, endSession, isCreating, isEnding } = useSleepSession();
|
|
const isSleeping = !!activeSession;
|
|
|
|
const handleClick = async () => {
|
|
if (!time) {
|
|
alert('Please select a valid time.');
|
|
return;
|
|
}
|
|
try {
|
|
if (isSleeping && activeSession?.id) {
|
|
await endSession({ sessionId: activeSession.id, endTime: time });
|
|
} else {
|
|
await createSession({ start_time: time });
|
|
}
|
|
} catch (error: unknown) {
|
|
console.error('Failed to update sleep session:', error instanceof Error ? error.message : error);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<button
|
|
onClick={handleClick}
|
|
disabled={isCreating || isEnding}
|
|
className={`w-full py-8 px-8 rounded-3xl text-2xl font-extrabold shadow-xl transition-all active:scale-95 flex items-center justify-center ${
|
|
isSleeping
|
|
? 'bg-rose-500 text-white hover:bg-rose-600 shadow-rose-200'
|
|
: 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-200'
|
|
} ${isCreating || isEnding ? 'opacity-50 cursor-not-allowed' : ''}`}
|
|
>
|
|
{isCreating || isEnding ? (
|
|
<div className="flex items-center space-x-2">
|
|
<span className="animate-spin rounded-full h-6 w-6 border-b-2 border-white"></span>
|
|
<span>Processing...</span>
|
|
</div>
|
|
) : isSleeping ? (
|
|
'Stop Sleep'
|
|
) : (
|
|
'Start Sleep'
|
|
)}
|
|
</button>
|
|
);
|
|
};
|
|
|
|
export default SleepButton;
|